Python-魔法函数__getattr__()与__getattribute__()的区别

  1. 如果某个类定义了 __getattribute__() 方法,在 每次引用属性或方法名称时 Python 都调用它(特殊方法名称除外,因为那样将会导致讨厌的无限循环)。
  2. 如果某个类定义了 __getattr__() 方法,Python 将只有在查找不到属性时才会调用它。如果实例 x 定义了属性 color, x.color 将 不会 调用x.__getattr__('color');而只会返回 x.color 已定义好的值
 1 class User:
 2     def __init__(self, name, info={}):
 3         self.name = name
 4         self.info = info
 5 
 6     def __getattr__(self, item):
 7         return self.info[item]
 8 
 9     #def __getattribute__(self, item):
10     #    return "getattribute item"
11 
12 if __name__ == "__main__":
13     user = User("tom", info={"phone":"12345678901", "age":20})
14     print(user.name)
15     print(user.age)

猜你喜欢

转载自www.cnblogs.com/Phantom3389/p/9247855.html