python魔法变量之__getattribute__,__getattr__

object.getattribute(self, name) 无条件调用,通过实例访问。如果类同时定义了getattr(),不会调用getattr()除非显式调用或产生了AttributeError。 object.getattr(self, name) 当未查找到访问的属性时,将会调用getattr()方法

In [49]: class T(object):
    ...:     a = 'hello'
    ...:     def __getattribute__(self, *args, **kwargs):
    ...:         print("called __getattribute__")
    ...:         return object.__getattribute__(self, *args, **kwargs)
    ...:     def __getattr__(self, name):
    ...:         print("called __getattr__")
    ...:         return name


In [50]: t = T()

In [51]: t.a
called __getattribute__
Out[51]: 'hello'

In [52]: t.b
called __getattribute__
called __getattr__
Out[52]: 'b'

Ref: 1.官方文档