← 中文资源

简体中文版本

cached_property 每实例只算一次

cached_property 把方法计算缓存到实例:首次访问执行,之后读缓存不再重算,computations 计数器证明只算一次。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

value      : 7.0
same cached: True
computed   : 1 time(s)

实现说明

cached_property 每实例只算一次以类 Report和函数 __init__、stats为骨架。

使用要点

  • 演示输出是带标签的(same cached:),每个操作都会留下自己的一行标注。
  • stats 是公开入口,文件里其余部分都是为它服务的内部实现。

常见问题

运行时需要 npm、pip、cargo 之类帮忙吗?

不需要——包管理器在这里无事可做,没有任何声明。 全部导入都来自标准库:functools。 文件在加载时定义 __init__、stats。

主要签名是 def stats(self)

核心语句

def __init__(self, numbers):
    self.numbers = numbers
    self.computations = 0
def stats(self):
    # 假装这是一次昂贵的聚合:只在首次访问时执行
    self.computations += 1
    return sum(self.numbers) / len(self.numbers)

代码示例

from functools import cached_property


class Report:
    def __init__(self, numbers):
        self.numbers = numbers
        self.computations = 0

    @cached_property
    def stats(self):
        # 假装这是一次昂贵的聚合:只在首次访问时执行
        self.computations += 1
        return sum(self.numbers) / len(self.numbers)


report = Report([3, 9, 12, 4])
first = report.stats
second = report.stats
print('value      :', first)
print('same cached:', first is second)
print('computed   :', report.computations, 'time(s)')