是否可以向用户创建的类添加字典功能?
即:
class Foo(object):
def __init__(self, x, y):
self.x
self.y
def __dict__(self):
return {'x': self.x, 'y': self.y}
f = Foo()
dict(f) <-- throws TypeError: iteration over non-sequence
最佳答案
dict
构造函数需要映射或可迭代的键/值对作为参数,因此您的类需要实现映射协议(protocol)或可迭代。
以下是如何使用后一种方法的示例:
class Foo(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __iter__(self):
return vars(self).iteritems()
使用示例:
>>> dict(Foo(2, 3))
{'x': 2, 'y': 3}
不过我不知道这有什么用。你可以这样做
>>> vars(Foo(2, 3))
{'x': 2, 'y': 3}
无需在类上实现 __iter__()
即可工作。
关于python - 将 python 的 dict 功能扩展到用户创建的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8168957/