实例化类时,为什么初始化属性时会调用__getattribute__

在交互式解释器中输入如下代码:
class A:
def init(self, x):
self.dict[‘x’] = x
def getattribute(self, attr):
print (‘开始执行 getattribute‘)
return object.getattribute(self, attr)

a = A(‘string’)

运行程序结果为:
开始执行 getattribute
为什么?

讨论数量: 2
Jason990420
self.__dict__['x'] = x

Will call self.__dict__ first, so __getattribute__ called. Use this statement for it,

self.x = x
4年前 评论

python 内,obj.name 该写法,都是直接通过调用 getattribute 方法从类属性中查找

4年前 评论