首页 > 解决方案 > 缓存非缓存属性

问题描述

是否有某种方法可以仅在更改类实例的某些输入属性时才缓存属性?在类实例的某些输入属性已更新后调用它们时,我想重新计算缓存的属性(并再次缓存它们)。

如果我有这样的课程:


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 并再次缓存它,直到实例的新更新。

标签: python

解决方案


您在谈论“属性”,但由于您提到输入参数,我认为您实际上指的是方法,因此您可以使用functools.lru_cache装饰器

例子:

@lru_cache
def count_vowels(sentence):
    sentence = sentence.casefold()
    return sum(sentence.count(vowel) for vowel in 'aeiou')

对于属性,有functools.cached_property


推荐阅读