擅长:python、mysql、java
<p>theodox的答案通常是好的,但是对于装饰师,您应该使用<code>functools.wraps</code>函数,如下例所示:</p>
<pre><code>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
</code></pre>
<p>它将保留原始docstrings、原始函数名(以及更多)。您可以在<a href="https://docs.python.org/3/library/functools.html#functools.wraps" rel="nofollow noreferrer">Python docs</a>中阅读更多有关它的信息。在</p>
<p>然后,假设前面的代码在<code>decorators</code>模块中,您应该按如下方式使用它:</p>
^{pr2}$
<p>注意,在代码示例中,它只是<code>@decorators.enable_video</code>,<strong>不是</strong><code>@decorators.enable_video(self)</code>。就像jornsharpe对您的问题的评论一样,在修饰时不会出现对<code>self</code>的引用。在</p>