Python 中的 __getattr__ 和 __getattribute__
Python 中 __getattr__ 和 __getattribute__ 有什么区别?何时使用哪个?
回答
屠龙少年
__getattribute__:每次访问属性时都会调用(无论属性是否存在)。__getattr__:仅在属性通过正常机制找不到时调用(属性不存在或引发 AttributeError)。
class Proxy:
def __init__(self, wrapped):
self._wrapped = wrapped
# 所有属性访问都经过此方法
def __getattribute__(self, name):
if name.startswith('_'):
return super().__getattribute__(name)
return getattr(self._wrapped, name)
# 仅在属性不存在时调用
def __getattr__(self, name):
return f'Default for {name}'
p = Proxy([1, 2])
print(p.count) # 获取底层 list 的 count 方法
print(p.undefined_attr) # 'Default for undefined_attr'
注意:
__getattribute__中易出现无限递归(应使用super().__getattribute__())- 优先使用
__getattr__(更安全,性能更好) - 只在需要拦截所有属性访问时用
__getattribute__