python __get__ __getattr__ __getattribute__

来源:互联网 发布:个性化简历推荐算法 编辑:程序博客网 时间:2024/06/05 01:20
class C(object):
    a = 'abc'
    def fun(self):
        print 'this fun'
    def __getattribute__(self, *args, **kwargs):
        print("__getattribute__() is called")
        return object.__getattribute__(self, *args, **kwargs)
    def __getattr__(self, name):
        print("__getattr__() is called ")
        return name + " from getattr"
    
    def __get__(self, instance, owner):
        print("__get__() is called", instance, owner)
        return self
    


class C2(object):
    d = C() 

if __name__ == '__main__':

   c = C()

  #以下访问存在的属性和方法,会调用__getattribute__

   c.fun() 

   c.a 

  #访问不存在的属性和方法,会先调用__getattribute__然后调用__getattr__

 c.b

  #类被引用时调用__get__

    c2 = C2()
    c2.d

0 0