VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > temp > python入门教程 >
  • 让属性具备惰性求值的能力

对某个属性进行访问的时候,不需要经过反复的计算再返回

  对属性的首次访问,将其值缓存起来,在其后的访问中,直接从缓存中取值,主要用来提高程序的性能

复制代码
"""
属性惰性求值
这里介入描述符就可以实现
"""


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

可见文本内容只打印了一次

 


  


相关教程