时间:2020-11-08 12:51:27 | 栏目:Python代码 | 点击:次
一个装饰器已经作用在一个函数上,你想撤销它,直接访问原始的未包装的那个函数。
假设装饰器是通过 @wraps 来实现的,那么你可以通过访问 wrapped 属性来访问原始函数:
>>> @somedecorator >>> def add(x, y): ... return x + y ... >>> orig_add = add.__wrapped__ >>> orig_add(3, 4) 7 >>>
如果有多个包装器:
In [588]: from functools import wraps In [589]: def decorator1(func): ...: @wraps(func) ...: def wrapper(*args, **kwargs): ...: print ('Decorator 1') ...: return func(*args, **kwargs) ...: return wrapper ...: In [590]: def decorator2(func): ...: @wraps(func) ...: def wrapper(*args, **kwargs): ...: print ('Decorator 2') ...: return func(*args, **kwargs) ...: return wrapper ...: In [591]: @decorator1 ...: @decorator2 ...: def add(x, y): ...: return x+y ...: In [592]: add(2,3) Decorator 1 Decorator 2 Out[592]: 5 In [593]: add.__wrapped__(2, 3) Decorator 2 Out[593]: 5 In [594]: add.__wrapped__.__wrapped__(2,3) Out[594]: 5
参考:Python Cookbook