如何在参数传递或条件匹配时用修饰符修饰函数

2024-05-17 16:53:29 发布

您现在位置:Python中文网/ 问答频道 /正文

这是带有参数的简单装饰器:

应用程序类型

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有条件地工作。你知道吗


Tags: theimportdecorators参数timeisvaluedef
3条回答

可以使用sys模块在windows命令行中使用参数运行Python脚本

使用python在终端中运行此代码应用程序类型True启用decorator,禁用decoratorpython应用程序类型python应用程序类型错误

import time
import sys

TIMING_ENABLED = True


def newdecorator():
    def benchmarking(funct):
        def timercheck(*args, **kwarg):
            if TIMING_ENABLED:
                starttime = time.time()
                print("starting time", time.time())
            funct(*args, **kwarg)
            if TIMING_ENABLED:
                print("TOTAL TIME TAKEN ::", time.time()-starttime)
        return timercheck
    return benchmarking

# passing value to the decorators with arguments


@newdecorator()
def tara():
    print("hellow testing")


if __name__ == "__main__":
    TIMING_ENABLED = sys.argv[1]
    tara()

您也可以在模块或其他名称空间中使用全局变量,但这可能只在您希望将此状态用于其他对象时才有用。配置装饰器行为的应用程序设置并不少见。你知道吗

import time

TIMING_ENABLED = True


def newdecorator():
    def benchmarking(funct):
        def timercheck(*args, **kwarg):
            if TIMING_ENABLED:
                starttime = time.time()
                print("starting time", time.time())
            funct(*args, **kwarg)
            if TIMING_ENABLED:
                print("TOTAL TIME TAKEN ::", time.time() - starttime)
        return timercheck
    return benchmarking

# passing value to the decorators with arguments


@newdecorator()
def tara():
    print("hellow testing")


if __name__ == "__main__":
    TIMING_ENABLED = False
    tara()

将条件检查放在timercheck函数中很重要,因为较低的作用域是在模块初始化期间执行的(在执行main()之前),我们将没有机会设置TIMING_ENABLED变量。你知道吗

如果你只希望这是一个开/关的事情,那么@Rawing的答案就是正确的选择。你知道吗

因为您不需要这个特定的装饰器的任何参数,所以您也可以简化它。我们在不使用()的情况下应用decorator,并且可以降低一级嵌套。另外,我们将functools.wraps装饰器添加到timecheck,这样这个函数看起来就像python的tara函数。(请参阅main中的附加说明),因为装饰程序实际上是用timecheck替换tara函数。你知道吗

from __future__ import print_function
import time
from functools import wraps

TIMING_ENABLED = True

def newdecorator(funct):
    @wraps(funct)
    def timercheck(*args, **kwarg):
        if TIMING_ENABLED:
            starttime=time.time()
            print("starting time",time.time())
        funct(*args, **kwarg)
        if TIMING_ENABLED:
            print("TOTAL TIME TAKEN ::",time.time()-starttime)
    return timercheck

@newdecorator
def tara():
    """Docs for tara function"""
    print("hellow testing")

if __name__=="__main__":
    TIMING_ENABLED = True
    print(tara.__name__, tara.__doc__)
    tara()

您总是可以删除@wraps(funct)行,并查看main将以不同的方式打印tara函数的内容。你知道吗

@decorator语法只是语法上的糖分。在引擎盖下,所发生的一切就是调用decorator时使用decorated函数作为其参数。你知道吗

因此,您可以在不使用decorator的情况下定义函数,然后在满足条件时应用decorator:

def tara():
    print("hellow testing")

if script_called_with_t_flag:
    tara = newdecorator('arg value')(tara)

相关问题 更多 >