1.__getattr__
和 __getattribute__
区别
1.
__getattr__
在访问对象的属性而属性不存在时触发
。它只会在属性不存在时调用,而对已存在的属性访问不会触发。2.
__getattribute__
在访问对象的任何属性时都会触发
。无论属性是否存在,每次属性访问都会经过__getattribute__
。
1.1使用__getattribute__
class A:
def __init__(self, x) -> None:
self.x = x
def __getattr__(self, name):
print('__getattr__')
def __getattribute__(self, __name: str):
print('__getattribute__')
print(__name)
return 222
a = A(1)
print(a.a)
print(a.z)
__getattribute__
a
222
__getattribute__
z
222
1.2使用__getattr__
from builtins import AttributeError
class A:
def __init__(self, x) -> None:
self.x = x
def __getattr__(self, name):
print('__getattr__')
def __getattribute__(self, __name: str):
print('__getattribute__')
print(__name)
AttributeError('not find')
a = A(1)
print(a.x)
print(a.z)
__getattribute__
x
None
__getattribute__
z
None
1.3用法
当使用
obj.undefined_attr
时,如果__getattribute__
存在,它会首先被调用。只有在__getattribute__
中抛出AttributeError
异常时,__getattr__
才会被调用。如果
__getattribute__
不存在,或者它没有引发AttributeError
异常,__getattr__
不会被调用。
class A:
def __init__(self, x) -> None:
self.x = x
def __getattr__(self, name):
print('__getattr__')
def __getattribute__(self, __name: str):
print('__getattribute__')
return object.__getattribute__(self, __name)
a = A(1)
print(a.x)
print(a.z)
__getattribute__
1
__getattribute__
__getattr__
None