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
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
theodox的答案通常是好的,但是对于装饰师,您应该使用
functools.wraps
函数,如下例所示:它将保留原始docstrings、原始函数名(以及更多)。您可以在Python docs中阅读更多有关它的信息。在
然后,假设前面的代码在
^{pr2}$decorators
模块中,您应该按如下方式使用它:注意,在代码示例中,它只是
@decorators.enable_video
,不是@decorators.enable_video(self)
。就像jornsharpe对您的问题的评论一样,在修饰时不会出现对self
的引用。在确实需要
self
引用吗?在更常见的是你会这样做
你可以这样运用它:
^{pr2}$如果由于某种原因,装饰师实际上需要自引用,那么您可以在哪里找到它。这个版本不包括以任何方式配置录像机,为此您将使用类而不是函数修饰符并将配置作为参数传递。在
相关问题 更多 >
编程相关推荐