@property
并@functools.lru_cache
已合并为@cached_property
。
import functools
class MyClass:
@functools.cached_property
def foo(self):
print("long calculation here")
return 21 * 2
您应该同时使用@property
和@functools.lru_cache
装饰器:
import functools
class MyClass:
@property
@functools.lru_cache()
def foo(self):
print("long calculation here")
return 21 * 2
该答案有更详细的示例,还提到了先前Python版本的反向移植。
Python Wiki具有一个缓存的属性装饰器(由MIT许可),可以这样使用:
import random
# the class containing the property must be a new-style class
class 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)
或者其他提及的任何实现都可以满足您的需求。 或上述反向端口。