是否有可能有条件地装饰一个功能.例如,我想使用timer函数(timeit)来装饰函数foo(),只有doing_performance_analysis为True(参见下面的伪代码).
if doing_performance_analysis:
@timeit
def foo():
"""
do something, timeit function will return the time it takes
"""
time.sleep(2)
else:
def foo():
time.sleep(2)
解决方法:
装饰器只是返回替换,可选择相同功能,包装器或完全不同的东西的callables.因此,您可以创建条件装饰器:
def conditional_decorator(dec, condition):
def decorator(func):
if not condition:
# Return the function unchanged, not decorated.
return func
return dec(func)
return decorator
现在您可以像这样使用它:
@conditional_decorator(timeit, doing_performance_analysis)
def foo():
time.sleep(2)
装饰者也可以是一个类:
class conditional_decorator(object):
def __init__(self, dec, condition):
self.decorator = dec
self.condition = condition
def __call__(self, func):
if not self.condition:
# Return the function unchanged, not decorated.
return func
return self.decorator(func)
这里__call__方法与第一个示例中返回的decorator()嵌套函数扮演相同的角色,此处的封闭dec和条件参数作为参数存储在实例中,直到应用装饰器为止.