考虑以下几点:
@property
def name(self):
if not hasattr(self, '_name'):
# expensive calculation
self._name = 1 + 1
return self._name
我是新手,但我认为缓存可以分解为装饰器。只是我没有找到喜欢的;)
PS 真正的计算不依赖于可变值
最佳答案
从 Python 3.2 开始有一个内置的装饰器:
@functools.lru_cache(maxsize=100, typed=False)
Decorator to wrap a function with a memoizing callable that saves up to the maxsize most recent calls. It can save time when an expensive or I/O bound function is periodically called with the same arguments.
用于计算的 LRU 缓存示例 Fibonacci numbers :
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)
>>> print([fib(n) for n in range(16)])
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]
>>> print(fib.cache_info())
CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)
如果您被 Python 2.x 困住,这里是其他兼容的内存库的列表:
functools32
| PyPI | Source code repoze.lru
| PyPI | Source code pylru
| PyPI | Source code backports.functools_lru_cache
| PyPI | Source code https://stackoverflow.com/questions/815110/