python decorator:
Memoization can be expressed naturally as a higher-order function, which can also be used as a decorator. The definition below creates a cache of previously computed results, indexed by the arguments from which they were computed. The use of a dictionary requires that the argument to the memoized function be immutable.
def memo(f):
cache = {}
def memoized(n):
if n not in cache:
cache[n] = f(n)
return cache[n]
return memoized
>>> counted_fib = count(fib)
>>> fib = memo(counted_fib)
>>> fib(19)
4181
>>> counted_fib.call_count
20
>>> fib(34)
5702887
>>> counted_fib.call_count
35
我们发现 call_count 的数目相比 recursive fib 明显变小了
更高级的 python 写法就是 decorator
def debug(func): # decorator: 接受一个函数作为参数,并返回另一个函数
def wrap(*args, **kwargs):
func(*args, **kwargs)
print("[DEBUG] '%s' model called." % (func.__name__))
return wrap
@debug
def testfunc():
print("Hello World")
testfunc()
...>
Hello World
[DEBUG] 'testfunc' model called.
...>
9.7
Charlie
海宁 CS61A_self_study