我正在用 python 编写一个类,并且我有一个需要相对较长时间来计算的属性,所以 我只想做一次。此外,类的每个实例都不需要它,所以 我不想在 __init__
中默认这样做。
我是 Python 新手,但不是编程新手。我可以很容易地想出一种方法来做到这一点,但我一遍又一遍地发现,做某事的“Pythonic”方法通常比我使用其他语言的经验想出的方法简单得多。
在 Python 中是否有“正确”的方法来做到这一点?
最佳答案
3.8 ≤ Python
@property
和 @functools.lru_cache
已合并为 @cached_property
.
import functools
class MyClass:
@functools.cached_property
def foo(self):
print("long calculation here")
return 21 * 2
3.2 ≤ Python < 3.8
您应该同时使用 @property
和 @functools.lru_cache
装饰器:
import functools
class MyClass:
@property
@functools.lru_cache()
def foo(self):
print("long calculation here")
return 21 * 2
This answer有更详细的示例,还提到了以前 Python 版本的反向移植。
Python < 3.2
Python wiki 有一个 cached property decorator (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)
或其他答案中提到的任何满足您需求的实现。
或者上面提到的backport。
关于python - 在 Python 中缓存类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4037481/