![python __getattr__和 __getattribute__ python __getattr__和 __getattribute__](https://image.shishitao.com:8440/aHR0cHM6Ly9ia3FzaW1nLmlrYWZhbi5jb20vdXBsb2FkL2NoYXRncHQtcy5wbmc%2FIQ%3D%3D.png?!?w=700&webp=1)
__getattr__
这个魔法函数会在类中查找不到属性时调用
class User:
def __init__(self):
self.info = 1 def __getattr__(self, item):
return 'not found attribute' if __name__ == "__main__":
user = User()
print(user.test)
__getattribute__
class User:
def __init__(self):
self.info = 1 def __getattribute__(self, item): # 只要是instance.property这种查找方式都会进入这个魔法函数
return "bobby" if __name__ == "__main__":
user = User()
print(user.info)
print(user.test)