实例查找属性的顺序:

类属性 > 数据描述符 > 实例属性 > 非数据描述符 > __getattr__

类属性>数据描述符>实例属性

class Str:
def __get__(self, instance, owner):
print("执行: __get__") def __set__(self, instance, value):
print("执行: __set__") def __delete__(self, instance):
print("执行: __delete__") class A:
name = Str() def __init__(self):
self.name = "mm" a = A()
A.name = "maotai_class" # 添加类属性 print(a.name) # 1.优先打印类属性 2.其次打印数据描述符 3.最后打印实例属性

实例属性>非数据描述符

class Str:
def __get__(self, instance, owner):
print("执行: __get__") # def __set__(self, instance, value):
# print("执行: __set__") # def __delete__(self, instance):
# print("执行: __delete__") class A:
name = Str() a = A()
a.name = "maotai"
print(a.__dict__) --
{'name': 'maotai'}
class Str:
def __get__(self, instance, owner):
print("执行: __get__") def __set__(self, instance, value):
print("执行: __set__") # def __delete__(self, instance):
# print("执行: __delete__") class A:
name = Str() a = A()
a.name = "maotai"
print(a.__dict__) --
执行: __set__
{}

非数据描述符>找不到

class A:
def __getattr__(self, item):
print("触发__getattr__") a = A()
a.xxx # 触发__getattr__
05-08 08:28