您可以使用缓存装饰器,让我们看一个示例
from functools import wraps
class FuncCache(object):
def __init__(self):
self.cache = {}
def __call__(self, func):
@wraps(func)
def callee(*args, **kwargs):
key = (args, str(kwargs))
# see is there already result in cache
if key in self.cache:
result = self.cache.get(key)
else:
result = func(*args, **kwargs)
self.cache[key] = result
return result
return callee
使用缓存装饰器,您可以在这里编写
my_cache = FuncCache()
@my_cache
def foo(n):
"""Expensive calculation
"""
sum = 0
for i in xrange(n):
sum += i
print 'called foo with result', sum
return sum
print foo(10000)
print foo(10000)
print foo(1234)
从输出中可以看出
called foo with result 49995000
49995000
49995000
foo 只会被调用一次。您不必更改函数 foo 的任何行。这就是装饰器的力量。