python - 缓存非缓存属性
问题描述
是否有某种方法可以仅在更改类实例的某些输入属性时才缓存属性?在类实例的某些输入属性已更新后调用它们时,我想重新计算缓存的属性(并再次缓存它们)。
如果我有这样的课程:
class C:
def __init__(self, a):
self.a=a
@cached_property
def expensive(self):
return 'some calculation which depends on the attribute "a"'
def dependent(self):
return 'some calculation which depends on the "C.expensive"'
当我第一次调用 C.dependent 时,它将调用 C.expensive 并缓存其输出以供将来调用。如果我用 Ca=new_value 更新我的实例,而不是调用 C.dependent,我想更新 C.expensive 并再次缓存它,直到实例的新更新。
解决方案
您在谈论“属性”,但由于您提到输入参数,我认为您实际上指的是方法,因此您可以使用functools.lru_cache装饰器
例子:
@lru_cache
def count_vowels(sentence):
sentence = sentence.casefold()
return sum(sentence.count(vowel) for vowel in 'aeiou')
推荐阅读
- flutter - 如何为 DataTable 添加阴影?
- ios - 为什么 URL 不能快速打开?
- python - 如何从文件名中提取艺术家姓名和歌曲名称?
- javascript - 使用 React.forwardRef 与自定义 ref 道具的价值
- javascript - 如何根据共同的属性将数组中的对象分组为数组数组
- reactjs - React JS:根据收到的状态渲染孩子
- qt - Qt 继承自 QWidget 类来自定义和使用它
- module - 在项目的库根目录中声明的模块中使用 Rust 特征
- arduino - 如何在 UnoArduSim 中使用七段
- swift - 在 Swift 中求和两个泛型值的最佳方法