开发者

In class definition inherited from dict why is there a difference in defining attributes?

In a class inherited from dict, why don't the two ways of defining an attribute produce the same result? Why do I see attr1 but not attr2?

class my_dict(dict):
   def __init__(self):
       dict.__init__(self)
       self['attr1'] = 'seen'
       setattr(self, 'attr2', 'unseen')

In [1]: x 开发者_开发问答= my_dict()

In [2]: x
Out[2]: {'attr1': 'seen'}


For the same reason that:

x = {}
x.foo = 34

doesn't work. dicts don't work by defining attributes.


x.attr2
# => 'unseen'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜