Python decorators
In python,a decorators starts with @,such as:
@myDecorator def func1(): print "inside func1()"
It means:
func1=myDecorator(func1)
Here is a useful decorator.
from functools import update_wrapper def decorator(d): "Make function d a decorator: d wraps a function fn." def _d(fn): return update_wrapper(d(fn), fn) update_wrapper(_d, d) return _d @decorator def memo(f): """Decorator that caches the return value for each call to f(args). Then when called again with same args, we can just look it up.""" cache = {} def _f(*args): try: return cache[args] except KeyError: cache[args] = result = f(*args) return result except TypeError: # some element of args can't be a dict key return f(*args) _f.cache = cache return _f
Then,implement it on fib
@memo def fib(n): if n == 0 or n == 1: return 1 else: return fib(n-1) + fib(n-2) print fib(100)
参考:
2012年6月25日 20:39
Decorator用于测试某一个方法挺好的。
2024年1月16日 17:25
Superb article. Thanks to this blog my expedition has actually ended.