Python≥3.8
@property并
@functools.lru_cache已合并为
@cached_property。
import functoolsclass MyClass: @functools.cached_property def foo(self): print("long calculation here") return 21 * 2Python≥3.2 <3.8
您应该同时使用
@property和
@functools.lru_cache装饰器:
import functoolsclass MyClass: @property @functools.lru_cache() def foo(self): print("long calculation here") return 21 * 2该答案有更详细的示例,还提到了先前Python版本的反向移植。
Python <3.2
Python
Wiki具有一个缓存的属性装饰器(由MIT许可),可以这样使用:
import random# the class containing the property must be a new-style classclass MyClass(object): # create property whose value is cached for ten minutes @cached_property(ttl=600) def randint(self): # will only be evaluated every 10 min. at maximum. return random.randint(0, 100)
或者其他提及的任何实现都可以满足您的需求。
或上述反向端口。



