acgtyrant acgtyrant - 1 year ago 91
Python Question

How to convert an custom class object to a tuple in Python?

If we define

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)

So we can convert its object to str immediately:

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

But as far as I know, there is not such
magic method, so I do not know how to define a class which can pass to
so that we can convert its object to tuple immediately.

Answer Source

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 return an iterator. 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)

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download