1:__getattr__
和__getattribute__
由于__getattr__
只针对未定义属性的调用,所以它可以在自己的代码中自由地获取其他属性,而__getattribute__
针对所有的属性运行,因此要十分注意避免在访问其他属性时,再次调用自身的递归循环。
class ClassA:
x = 'a'
def __init__(self):
self.y = 'b'
def __getattribute__(self, item):
print(item)
pass
def __getattr__(self, item):
print("__getattr")
return '__getattr__'+item
if __name__ == '__main__':
a = ClassA()
print(a.x) # a
# 使用实例对象直接访问实例存在的实例属性时,不会调用__getattr__方法
print(a.y) # b
# 使用实例对象直接访问实例不存在的实例属性时,会调用__getattr__方法
print(a.z) # __getattr__
>>>
x
None
y
None
z
None
__getattribute__
和__getattr__
都是对访问属性时的特殊操作
-
__getattr__
只针对未定义属性的调用 -
__getattribute__
针对所有的属性运行 - 当代码中同时重写
__getattr__
和__getattribute__
时候,不会调用__getattr__
2023-04-28
网友评论