是否有一个装饰器来简单地缓存函数返回值?考虑以下:@propertydef name(self):
if not hasattr(self, '_name'):
# expensive calculation
self._name = 1 + 1
return self._name我是新手,但我认为缓存可能会被装入装饰器中。只有我找不到喜欢它的人;)PS真正的计算不依赖于可变值
3 回答

Smart猫小萌
TA贡献1911条经验 获得超7个赞
从Python 3.2开始,有一个内置的装饰器:
@functools.lru_cache(maxsize=100, typed=False)
Decorator用一个memoizing callable来包装一个函数,它可以节省maxsize最近的调用。当使用相同的参数定期调用昂贵的或I / O绑定函数时,它可以节省时间。
用于计算Fibonacci数的LRU高速缓存示例:
@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,这里有一个其他兼容的memoization库列表:

交互式爱情
TA贡献1712条经验 获得超3个赞
class memorize(dict): def __init__(self, func): self.func = func def __call__(self, *args): return self[args] def __missing__(self, key): result = self[key] = self.func(*key) return result
样品用途:
>>> @memorize... def foo(a, b):... return a * b>>> foo(2, 4)8>>> foo{(2, 4): 8}>>> foo('hi', 3)'hihihi'>>> foo{(2, 4): 8, ('hi', 3): 'hihihi'}
添加回答
举报
0/150
提交
取消