您的位置:首页 > 编程语言 > Python开发

python __get__ __getattr__ __getattribute__

2014-07-16 11:53 337 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: