27

If we define __str__ method in a class:

    class Point():
        def __init__(self, x, y):
            self.x = x
            self.y = y


        def __str__(self, key):
            return '{}, {}'.format(self.x, self.y)

We will be able to define how to convert the object to the str class (into a string):

    a = Point(1, 1)
    b = str(a)
    print(b)

I know that we can define the string representation of a custom-defined object, but how do we define the list —more precisely, tuple— representation of an object?

theX
  • 1,008
  • 7
  • 22
acgtyrant
  • 1,721
  • 1
  • 16
  • 24
  • 4
    Give us some example code of something you would like to convert to a tuple so we can help. Also check this: http://stackoverflow.com/questions/12836128/python-convert-list-to-tuple -> It is specific to lists but it might help you. – Angelos Chalaris Jun 05 '16 at 07:11

1 Answers1

42

The tuple "function" (it's really a type, but that means you can call it like a function) will take any iterable, including an iterator, as its argument. So if you want to convert your object to a tuple, just make sure it's iterable. This means implementing an __iter__ method, which should be a generator function (one whose body contains one or more yield expressions). e.g.

>>> class SquaresTo:
...     def __init__(self, n):
...         self.n = n
...     def __iter__(self):
...         for i in range(self.n):
...             yield i * i
...
>>> s = SquaresTo(5)
>>> tuple(s)
(0, 1, 4, 9, 16)
>>> list(s)
[0, 1, 4, 9, 16]
>>> sum(s)
30

You can see from the example that several Python functions/types will take an iterable as their argument and use the sequence of values that it generates in producing a result.

holdenweb
  • 33,305
  • 7
  • 57
  • 77
  • 1
    I find we can [define `__getitem__` method to make the class iterable](http://stackoverflow.com/questions/926574/why-does-defining-getitem-on-a-class-make-it-iterable-in-python) too. – acgtyrant Jun 05 '16 at 07:55
  • I explained the iteration protocols in [a talk to PyData London](https://github.com/steveholden/iteration) earlier this year. It might help - there is [also a video of the session](https://www.youtube.com/watch?v=iTwrF1DofCY). – holdenweb Jun 05 '16 at 08:52