Python 的 缓存属性
等级 5355 次按键
这使用@cached_property缓存昂贵的计算。属性只计算一次并存储在实例中。
Python 代码
# 从functools导入cached_property# 缓存属性方法的返回值1from functools import cached_property# 导入time用于模拟慢计算2import time3 # ExpensiveCalculation有一个慢计算# 我们想避免重新计算结果4class ExpensiveCalculation: # __init__存储输入值5 def __init__(self, value: int):6 self.value = value7 # @cached_property计算一次,缓存结果 # 后续访问返回缓存值8 @cached_property # result是昂贵的属性 # 返回类型是int9 def result(self) -> int: # 打印以显示计算何时发生10 print("Computing...") # 模拟慢操作11 time.sleep(0.1) # 返回平方值12 return self.value ** 213 # 用值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