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()
c2.d
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