我在一个类中有一些属性方法,我想在某个时候清除此属性的缓存。
范例:
class Test():
def __init__(self):
pass
@property
@functools.lru_cache()
def prop(self):
# Compute some stuffs and return complex number
Run Code Online (Sandbox Code Playgroud)
如果我做self.prop.clear_cache(),在这里我得到以下错误信息:
AttributeError: 'numpy.complex128' object has no attribute 'cache_clear'
Run Code Online (Sandbox Code Playgroud)
clear_cache()适用于函数,但不适用于属性方法。有什么办法吗?
您需要访问属性对象的getter属性上的缓存属性,因此.fget。您只能访问类上的属性对象:
Test.prop.fget.cache_clear()
Run Code Online (Sandbox Code Playgroud)
这是因为@property装饰器prop使用属性实例将功能对象替换为LRU缓存。
访问实例上的属性名称将始终为您提供属性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
Run Code Online (Sandbox Code Playgroud)
请注意,以这种方式使用LRU缓存意味着该缓存存储在该类的所有实例之间共享,并且每个实例存储有单独的结果(缓存在self参数上键入)。清除缓存将清除所有实例。给定默认maxsize=128配置,这意味着将仅缓存最近使用的128个实例的属性值。访问实例#129上的属性,然后再次访问实例#1将意味着重新计算#1的值,因为该实例的属性值将被逐出。