我想定义一个类,以便它的实例可以转换为tuple和dict.一个例子:
class Point3:
...
p = Point(12, 34, 56)
tuple(p) # gives (12, 34, 56)
dict(p) # gives { 'x': 12, 'y': 34, 'z': 56 }
Run Code Online (Sandbox Code Playgroud)
我发现如果我定义__iter__为一个产生单个值的迭代器,那么实例可以被转换为tuple,如果它产生双值,那么它可以被转换为dict:
class Point3:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
# This way makes instance castable to tuple
def __iter__(self):
yield self.x
yield self.y
yield self.z
# This way makes instance castable to dict
def __iter__(self):
yield …Run Code Online (Sandbox Code Playgroud)