请思考带参数的@decorator,@functools.wraps应该放置在哪:
def performance(unit): def perf_decorator(f): def wrapper(*args, **kw): ??? return wrapper return perf_decorator
注意@functools.wraps应该作用在返回的新函数上。
参考代码:
import time, functools def performance(unit): def perf_decorator(f): @functools.wraps(f) def wrapper(*args, **kw): t1 = time.time() r = f(*args, **kw) t2 = time.time() t = (t2 - t1) * 1000 if unit==‘ms‘ else (t2 - t1) print ‘call %s() in %f %s‘ % (f.__name__, t, unit) return r return wrapper return perf_decorator @performance(‘ms‘) def factorial(n): return reduce(lambda x,y: x*y, range(1, n+1)) print factorial.__name__
原文地址:http://blog.csdn.net/qq_20480611/article/details/46627985