版权声明:17602128911 https://blog.csdn.net/bus_lupe/article/details/86410041
# 类 > 数据描述符 > 实例 > 非数据描述符
# 数据描述符有__get__、__set__方法
# 非数据描述符没有__set__方法
'''
设置缓存,将函数计算值存储到实例属性,再次获取由于实例优先级大于非数据描述符会直接
从实例取,不会出发非数据描述符的__get__方法
'''
# 定义描述符
class Lazyproperty:
def __init__(self, func):
# self.func = Room.area
self.func = func
def __get__(self, instance, owner): # r1, Room
print('get')
# 直接用类调用返回Lazyproperty实例
if instance is None:
return self
res = self.func(instance) # Room.func(r1)
# 将函数运算结果存储到实例属性,实例优先级大于非数据描述符,下次获取直接从
# 实例获取不会触发非数据描述符的__get__方法
setattr(instance, self.func.__name__, res) # r1.area = res
return res
# 定义类
class Room:
def __init__(self, name, width, length):
self.name = name
self.width = width
self.length = length
# @Lazyproperty => area = Lazyproperty(area)
# area是Lazyproperty类的实例
# 类似定义的非数据描述符,实例调用area属性的时候,触发Lazyproperty的__get__方法
@Lazyproperty
def area(self):
return self.width * self.length
r1 = Room('bedroom', 5, 3)
print(r1.area)
print(r1.area)
print(r1.area)
print(r1.area)
'''
get
15
15
15
15
'''