__getattr__ 与 __getattribute__ 的区别

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class C:
def __getattr__(self, name):
return '[private]' + object.__getattribute__(self, name)

def __getattribute__(self, name):
if name.startswith('_'):
raise AttributeError('name is not exist')
return object.__getattribute__(self, name)

c = C()
c._name = 'guanyu'
print(c._name)

c.age = 88
print(c.age)
  1. 在旧式类中不存在这两个属性,而python3中都是新式类。以上代码为python3。
  2. 通过实例访问属性时,都会调用__getattribute__,若访问属性需要调用object.__getattribute__(self, *args, **kwargs)。直接调用自身属性会引发异常,python3引发RecursionError: maximum recursion depth exceeded while calling a Python object。python2引发RuntimeError: maximum recursion depth exceeded while calling a Python object
  3. 当属性不存在或者__getattribute__引发AttributeError异常时。会调用__getattr__