是否可以有条件地装饰函数? For example, I want to decorate the function foo()
with a timer function ( timeit
), but only when doing_performance_analysis
condition is True
,像这样:
if doing_performance_analysis:
@timeit
def foo():
"""
Do something, e.g. sleep, and let timeit
return the time it takes
"""
time.sleep(2)
else:
def foo():
time.sleep(2)
原文由 cfpete 发布,翻译遵循 CC BY-SA 4.0 许可协议
装饰器是简单的可调用对象,返回一个替换,可选的相同函数、包装器或完全不同的东西。因此,您可以创建一个条件装饰器:
现在你可以像这样使用它:
装饰器也可以是一个类:
Here the
__call__
method plays the same role as the returneddecorator()
nested function in the first example, and the closed-overdec
andcondition
此处的参数在应用装饰器之前存储为实例的参数。