这是带有参数的简单装饰器:
应用程序类型
from __future__ import print_function
import time
def newdecorator(arg1):
def benchmarking(funct):
#The argument is accessible here
print("this is the value of argument",arg1)
def timercheck(*args, **kwarg):
starttime=time.time()
print("starting time",time.time())
funct(*args, **kwarg)
print("TOTAL TIME TAKEN ::",time.time()-starttime)
return timercheck
return benchmarking
#passing value to the decorators with arguments
@newdecorator('arg value')
def tara():
print("hellow testing")
if __name__=="__main__":
tara()
装修工工作得很好。它用一个函数来装饰函数,以显示开始时间和它所花费的时间。你知道吗
我想要达到的目标: 我是说,我希望装饰器有条件地实现。你知道吗
when a user runs app.py let the decorators not be implemented
user runs app.py -t than want the decorators to be implemented
我将使用argparse模块进行参数解析,这不是一个大问题,我想知道的是如何使decorator有条件地工作。你知道吗
可以使用sys模块在windows命令行中使用参数运行Python脚本
使用python在终端中运行此代码应用程序类型True启用decorator,禁用decoratorpython应用程序类型或python应用程序类型错误
您也可以在模块或其他名称空间中使用全局变量,但这可能只在您希望将此状态用于其他对象时才有用。配置装饰器行为的应用程序设置并不少见。你知道吗
将条件检查放在
timercheck
函数中很重要,因为较低的作用域是在模块初始化期间执行的(在执行main()
之前),我们将没有机会设置TIMING_ENABLED
变量。你知道吗如果你只希望这是一个开/关的事情,那么@Rawing的答案就是正确的选择。你知道吗
因为您不需要这个特定的装饰器的任何参数,所以您也可以简化它。我们在不使用
()
的情况下应用decorator,并且可以降低一级嵌套。另外,我们将functools.wraps
装饰器添加到timecheck
,这样这个函数看起来就像python的tara
函数。(请参阅main
中的附加说明),因为装饰程序实际上是用timecheck
替换tara
函数。你知道吗您总是可以删除
@wraps(funct)
行,并查看main
将以不同的方式打印tara
函数的内容。你知道吗@decorator
语法只是语法上的糖分。在引擎盖下,所发生的一切就是调用decorator时使用decorated函数作为其参数。你知道吗因此,您可以在不使用decorator的情况下定义函数,然后在满足条件时应用decorator:
相关问题 更多 >
编程相关推荐