先上一段代码:
class MyClass(object): v1 = 1 def __getattribute__(self, *args, **kwargs): print '__getattribute__' return object.__getattribute__(self, *args, **kwargs) def __getattr__(self, name): print '__getattr__' return name def __get__(self, instance, owner): print '__get__' return self class MyClass2(object): d = MyClass() if __name__ == '__main__': c = MyClass() c2 = MyClass2() print '-------- c.v1 --------' print c.v1 print '-------- c.v2 --------' print c.v2 print '-------- c2.d --------' print c2.d print '-------- MyClass.v1 --------' print MyClass.v1运行结果:
-------- c.v1 -------- __getattribute__ 1 -------- c.v2 -------- __getattribute__ __getattr__ v2 -------- c2.d -------- __get__ <__main__.MyClass object at 0x101050f90> -------- MyClass.v1 -------- 1可以看到:
访问c1的v1属性,直接调用getattribute方法。访问c1的v2属性(不存在),先调用getattribute方法,没有找到这个属性,再调用getattr方法。访问c2的d属性(它是MyClass的一个实例),将调用MyClass的get方法。访问MyClass的v1属性,不会调用getattribute和getattr方法。