您可以使用一個緩存裝飾,讓看一個例子
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的任何一行。這是裝飾者的力量。
我不確定這通常是什麼意思* lazy *。更安全地稱它*緩存*或*記憶*。 – 2011-03-14 05:29:00
@John Y是對的:「懶惰評估」是指不計算不會影響包含表達式結果的表達式的結果,例如。在'f()和g()'中,如果f()是'False',懶惰評估將不會調用'g()'。這個問題不是關於這個問題。 – detly 2011-03-14 05:39:59
當有函數參數時,它是memoization。否則,它只是一個懶惰的函數調用。 – 2011-03-14 05:41:09