IT评测·应用市场-qidao123.com

标题: 让属性具备惰性求值的能力 [打印本页]

作者: 麻花痒    时间: 2023-5-22 15:43
标题: 让属性具备惰性求值的能力
对某个属性进行访问的时候,不需要经过反复的计算再返回
  对属性的首次访问,将其值缓存起来,在其后的访问中,直接从缓存中取值,主要用来提高程序的性能
  1. """
  2. 属性惰性求值
  3. 这里介入描述符就可以实现
  4. """
  5. class LazyProperty:
  6.     def __init__(self, func):
  7.         self.func = func
  8.     def __get__(self, instance, owner):
  9.         if instance is None:
  10.             return self
  11.         value = self.func(instance)
  12.         setattr(instance, self.func.__name__, value)
  13.         return value
  14. class Valley:
  15.     @LazyProperty
  16.     def age(self):
  17.         print("shi_xiao_gu_a")
  18.         return 2 * 13
  19. v = Valley()
  20. print(v.age)
  21. print(v.age)
复制代码
output: 
  shi_xiao_gu_a
  26
  26
可见文本内容只打印了一次
 

  

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!




欢迎光临 IT评测·应用市场-qidao123.com (https://dis.qidao123.com/) Powered by Discuz! X3.4