__get__ __getattr__ __getattribute__ 的区别

class A:

def __init__(self, a):
self.a = a

# def __new__(cls, *args, **kwargs):
# print("__new__")

# 如果class定义了__get__,则这个class就称为descriptor。owner是所有者的类,instance是访问 descriptor的实例,如果不是通过实例访问,而是通过类访问的话,instance则为None。
# (descriptor的实例自己访问自己是不 会触发__get__,而会触发__call__,只有descriptor作为其它类的属性才有意义。)
def __get__(self, instance, owner):
print("visiting this item:", instance, owner)
return self

def __getattr__(self, item):
print("no this item:", item)

def __getattribute__(self, item): # 无条件被调用,通过实例访问属性
print("__getattribute__:", item)
return object.__getattribute__(self, item)


a = A(2)
print(a.a)
a.b
class B:
b=A(2)

print("***********")
print(B().b) # b引用a,才会触发__get__
原文地址:https://www.cnblogs.com/sylarwang/p/14276507.html