gpt4 book ai didi

python - 清除@property方法python的缓存

转载 作者:行者123 更新时间:2023-11-28 21:32:56 30 4
gpt4 key购买 nike

我在一个类中有一些属性方法,我想在某个时候清除这个属性的缓存。

示例:

class Test():
def __init__(self):
pass

@property
@functools.lru_cache()
def prop(self):
# Compute some stuffs and return complex number

如果我执行 self.prop.clear_cache(),这里是我得到的错误消息:

AttributeError: 'numpy.complex128' object has no attribute 'cache_clear'

clear_cache() 适用于函数,但不适用于属性方法。有什么办法吗?

最佳答案

需要在property对象的getter属性上访问缓存属性,所以.fget。您只能在类上访问属性对象:

Test.prop.fget.cache_clear()

那是因为 @property 装饰器用 LRU 缓存替换了 prop 函数对象,带有一个属性实例。

访问实例 上的属性名称将始终为您提供属性 getter 的结果,而不是具有缓存控件的函数对象。

演示:

>>> import functools
>>> class Foo:
... @property
... @functools.lru_cache()
... def bar(self):
... print("Accessing the bar property")
... return 42
...
>>> f = Foo()
>>> f.bar
Accessing the bar property
42
>>> f.bar # cached
42
>>> Foo.bar.fget.cache_clear()
>>> f.bar
Accessing the bar property
42

请注意,以这种方式使用 LRU 缓存意味着缓存存储在类的所有实例之间共享,每个实例存储单独的结果(缓存以 self 参数为键)。清除缓存将为所有实例清除它。给定默认的 maxsize=128 配置,这意味着只会缓存最近使用的 128 个实例的属性值。访问实例 #129 上的属性,然后再次访问实例 #1 将意味着为 #1 重新计算该值,因为该实例的属性值将被逐出。

关于python - 清除@property方法python的缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55497353/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com