[英]Python “__setattr__” and “__getattribute__” confusion
[英]Python __getattribute__ and __setattr__
我有以下代码:
#-*-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__
? 这是我的想法: __init__
有self.x = x
,并且__setattr__
捕获__init__
, self.__dict__[name] = value
捕获__getattrbute__
。 因此,将调用__getattribute__
。 我的想法对吗? 怎么了 ?
箭头指向__setattr__
调用__getattribute__
:
def __setattr__(self, name, value):
print "set:", name, value
self.__dict__[name] = value
# ^ attribute access!
__getattribute__
处理所有显式的属性查找,包括__dict__
。 我相信这是您已经得出的结论; 我不太明白你想说什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.