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. dict
s don't work by defining attributes.
x.attr2
# => 'unseen'
精彩评论