我有以下代码:
#-*-coding:utf-8-*-
class A(object):
def __init__(self, x):
self.x = x
def __getattr__(self, name): # `__getattr__` will be called undefined attribute
print "get: ", name
return self.__dict__.get(name)
def __setattr__(self, name, value):
print "set:", name, value
self.__dict__[name] = value
def __getattribute__(self, name): # `__getattribute__` will be called all attributes
print "attribute:", name
return object.__getattribute__(self, name)
if __name__ == "__main__":
a = A(10)
print '---------------'
a.x
print '---------------'
a.y = 20
print '---------------'
a.z
结果是:
set: x 10
attribute: __dict__
---------------
attribute: x
---------------
set: y 20
attribute: __dict__
---------------
attribute: z
get: z
attribute: __dict__
当我拨打a=A(10)
时,为什么会调用__getattribute__
?这是我的想法:self.x = x
中有__init__
,__setattr__
抓住__init__
,self.__dict__[name] = value
抓住__getattrbute__
。因此,__getattribute__
被调用。我的想法是对的吗?怎么了?
答案 0 :(得分:2)
箭头指向__setattr__
调用__getattribute__
的位置:
def __setattr__(self, name, value):
print "set:", name, value
self.__dict__[name] = value
# ^ attribute access!
__getattribute__
处理所有显式属性查找,包括__dict__
。我相信这是你已经得出的结论;我不太明白你想说什么。