Python __getattribute__、__getattr__、__get__总结

来源:互联网 发布:笔记本触摸屏锁定软件 编辑:程序博客网 时间:2024/06/05 05:19

先上一段代码:

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 selfclass 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

可以看到:

  1. 访问c1的v1属性,直接调用getattribute方法。
  2. 访问c1的v2属性(不存在),先调用getattribute方法,没有找到这个属性,再调用getattr方法。
  3. 访问c2的d属性(它是MyClass的一个实例),将调用MyClass的get方法。
  4. 访问MyClass的v1属性,不会调用getattributegetattr方法。
0 0
原创粉丝点击