__getattr__和__getattribute__区别

发布时间 2024-01-07 02:53:48作者: lxd670

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