28

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?

1
  • 4
    Give us some example code of something you would like to convert to a tuple so we can help. Also check this: stackoverflow.com/questions/12836128/… -> It is specific to lists but it might help you. Commented Jun 5, 2016 at 7:11

1 Answer 1

46

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I explained the iteration protocols in a talk to PyData London earlier this year. It might help - there is also a video of the session.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.