开发者

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

开发者 https://www.devze.com 2023-01-10 05:39 出处:网络
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?

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

精彩评论

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