1
是否可以向用戶創建的類添加dict功能?將python的詞典功能擴展到用戶創建的類
即:
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(),或者你會寧願它像一個字典,所以你可以做'f = Foo();打印f ['x']'?兩者都是可能的。 – six8