转自:https://www.cnblogs.com/astropeak/p/9029104.html
- 装饰器例
- 多重装饰
装饰器例
from functools import wraps def trace(name): def wrapper(func): @wraps(func) #名称修正 def wrapped(*args, **kwargs): print('Enter %s. Args: %s, kwargs: %s' % (name, args, kwargs)) rv = func(*args, **kwargs) print('Exit %s. Return value: %s' % (name, rv)) return rv return wrapped return wrapper @trace('area') def area(height, width): print('area called') return height * width area(2, 3)
结果为
Enter area. Args: (2, 3), kwargs: {} area called Exit area. Return value: 6多重装饰
@decSec @decFir def foo():pass
等价于:
def foo():pass foo = decFir(foo) foo = decSec(foo)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)