我对Python 2.7中的子类化行为有疑问.
如果我从内置dict类型继承,它似乎__ dict __总是空的.Python在哪里保存键/值对?
>>> class Foobar(dict):
... pass
...
>>> foobar = Foobar()
>>> foobar.__dict__
{}
>>> foobar['test'] = 1
>>> foobar.__dict__
{}
>>>
Run Code Online (Sandbox Code Playgroud)
__dict__是存储对象属性的位置.Dicts的项目不是属性,它们是项目.大多数dicts没有数据属性.
BTW:dict根据你想要实现的目标,很难正确地进行子类化.例如,您可以覆盖其__setitem__方法,但update不会使用它.
dict类纯粹在C中作为内置实现.它的数据存储对于该实现是私有的.
作为一个思想实验,想象一下如果它将名称/值对放入Python dict中,那dict将如何存储它们?在另一个Python dict?然后,好吧,你明白了!
部分答案是你误解了目的__dict__.__dict__用于存储属性,而不是项目,它存在于大多数用户定义的对象中.实际上,如果dict以适当的方式进行子类化,__dict__ 则会在其中包含值.
>>> class Foo(dict):
... def __init__(self, *args, **kwargs):
... super(Foo, self).__init__(*args, **kwargs)
... self.banana = 'banana'
... self['banana'] = 'not really a banana'
...
>>> f = Foo()
>>> f.__dict__
{'banana': 'banana'}
>>> f.banana
'banana'
>>> f['banana']
'not really a banana'
Run Code Online (Sandbox Code Playgroud)