Python 的 缓存属性

等级 5355 次按键

这使用@cached_property缓存昂贵的计算。属性只计算一次并存储在实例中。

Python 代码

# 从functools导入cached_property
# 缓存属性方法的返回值
1from functools import cached_property
# 导入time用于模拟慢计算
2import time
3
# ExpensiveCalculation有一个慢计算
# 我们想避免重新计算结果
4class ExpensiveCalculation:
# __init__存储输入值
5 def __init__(self, value: int):
6 self.value = value
7
# @cached_property计算一次,缓存结果
# 后续访问返回缓存值
8 @cached_property
# result是昂贵的属性
# 返回类型是int
9 def result(self) -> int:
# 打印以显示计算何时发生
10 print("Computing...")
# 模拟慢操作
11 time.sleep(0.1)
# 返回平方值
12 return self.value ** 2
13
# 用值5创建实例
14obj = ExpensiveCalculation(5)
# 第一次访问计算并缓存结果
# 打印"Computing..."然后"First: 25"
15print(f"First: {obj.result}")
# 第二次访问使用缓存值
# 不打印"Computing..."
16print(f"Second: {obj.result}")
# 第三次访问也使用缓存值
# 仍然不打印"Computing..."
17print(f"Third: {obj.result}")

运行结果

Computing...
First: 25
Second: 25
Third: 25
用这段代码练习打字

可以用这段代码练习打字。成绩不会计入排行榜。

这段代码中的符号

这段 Python 代码中需要输入的符号及其出现次数。

  • .× 10
  • "× 8
  • (× 8
  • )× 8
  • :× 7
  • _× 6
  • {× 3
  • }× 3
  • *× 2
  • =× 2

Python 等级 5 的更多代码示例

← 返回 Python 打字练习