对某个属性进行访问的时候,不需要经过反复的计算再返回
对属性的首次访问,将其值缓存起来,在其后的访问中,直接从缓存中取值,主要用来提高程序的性能- """
- 属性惰性求值
- 这里介入描述符就可以实现
- """
- class LazyProperty:
- def __init__(self, func):
- self.func = func
- def __get__(self, instance, owner):
- if instance is None:
- return self
- value = self.func(instance)
- setattr(instance, self.func.__name__, value)
- return value
- class Valley:
- @LazyProperty
- def age(self):
- print("shi_xiao_gu_a")
- return 2 * 13
- v = Valley()
- print(v.age)
- print(v.age)
复制代码 output:
shi_xiao_gu_a
26
26
可见文本内容只打印了一次
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |