实例化类时,为什么初始化属性时会调用__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
3年前 评论

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

3年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!