加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 如果你从dict继承,为什么__dict__总是空的?

发布时间:2020-12-20 12:39:56 所属栏目:Python 来源:网络整理
导读:我对 Python 2.7中的子类化行为有疑问. 如果我从内置的dict类型继承,似乎__ dict __总是为空. Python在哪里保存键/值对? class Foobar(dict):... pass... foobar = Foobar() foobar.__dict__{} foobar['test'] = 1 foobar.__dict__{} 解决方法 部分答案是你
我对 Python 2.7中的子类化行为有疑问.

如果我从内置的dict类型继承,似乎__ dict __总是为空.
Python在哪里保存键/值对?

>>> class Foobar(dict):
...     pass
... 
>>> foobar = Foobar()
>>> foobar.__dict__
{}
>>> foobar['test'] = 1
>>> foobar.__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'

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读