Python decorator:在tes之前运行decorator

2024-06-16 12:24:58 发布

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

我希望添加一个在某些测试中运行录像机的decorator,如下所示:

@decorators.video(self)
def test_1234(self):
    ...

我很难将自变量传递到decorator,因为它需要一些属性。我该怎么做?在


Tags: testselfdecorators属性defvideodecorator录像机
2条回答

theodox的答案通常是好的,但是对于装饰师,您应该使用functools.wraps函数,如下例所示:

from functools import wraps

def enable_video(fn)
    '''Decorate the function to start video, call the function, stop video.'''
    @wraps(fn)
    def inner(*args, **kwargs): 
    # could be just `def inner(self):` if only intended to use
    # with methods without arguments and keyword arguments
        do_stuff_before()
        fn(*args, **kwargs)
        do_stuff_after()
    return inner

它将保留原始docstrings、原始函数名(以及更多)。您可以在Python docs中阅读更多有关它的信息。在

然后,假设前面的代码在decorators模块中,您应该按如下方式使用它:

^{pr2}$

注意,在代码示例中,它只是@decorators.enable_video不是@decorators.enable_video(self)。就像jornsharpe对您的问题的评论一样,在修饰时不会出现对self的引用。在

确实需要self引用吗?在

更常见的是你会这样做

def enable_video(fn):
    '''decorate the test function so it starts the video, runs the test, and stop the video'''   
    def video_aware_test(self_refrence):
       start_video_recorder()
       try:
          fn()
       finally:
          stop_video_recorder()
    return video_aware_test

你可以这样运用它:

^{pr2}$

如果由于某种原因,装饰师实际上需要自引用,那么您可以在哪里找到它。这个版本不包括以任何方式配置录像机,为此您将使用类而不是函数修饰符并将配置作为参数传递。在

相关问题 更多 >