Python 继承自dict的类内定义为何在定义属性方面存在差异?
在从dict继承的类中,为什么定义属性的两种方法不能产生相同的结果?为什么我看到的是attr1而不是attr2Python 继承自dict的类内定义为何在定义属性方面存在差异?,python,Python,在从dict继承的类中,为什么定义属性的两种方法不能产生相同的结果?为什么我看到的是attr1而不是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': '
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'}
出于同样的原因:
x = {}
x.foo = 34
不起作用dict
s不能通过定义属性来工作
x.attr2
# => 'unseen'