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

天涯浪子 提交于 2019-11-30 21:57:06

问题


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)

So we can convert its object to str immediately:

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

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


回答1:


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.



来源:https://stackoverflow.com/questions/37639363/how-to-convert-an-custom-class-object-to-a-tuple-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!