装饰器(Decorator)
定义
* 想要增强目标函数的功能,但又不希望修改目标函数的内部定义
- 在代码运行期间动态增加功能
举例
目标函数
>>> def now(): ... print '2013-12-25' ... >>> f = now >>> f() 2013-12-25
不需要传入参数的装饰器函数
import functools def log(func): @functools.wraps(func) def wrapper(*args, **kw): print 'call %s():' % func.__name__ return func(*args, **kw) return wrapper
调用装饰器:
@log def now(): print '2013-12-25' >>> now() call now(): 2013-12-25
需要传入参数的装饰器函数
import functools def log(text): def decorator(func): @functools.wraps(func) def wrapper(*args, **kw): print '%s %s():' % (text, func.__name__) return func(*args, **kw) return wrapper return decorator
调用装饰器:
@log('execute') def now(): print '2013-12-25' >>> now() execute now(): 2013-12-25
@functools.wraps(func) 的作用
- 保证原始函数的name等属性复制到wrapper()函数中;
- 否则,被装饰的 now() 函数的 name 属性的值变成了「wrapper 」;
- 有些依赖函数签名的代码执行就会出错