擅长:python、mysql、java
<p>如果您对其进行修改并添加一点:</p>
<pre><code>print('hi')
with MyFunctionDecorator(print, reverse_decorator) as print:
print('hello')
print('bye')
</code></pre>
<p>下面是一个适用于此示例的定义*:</p>
^{pr2}$
<hr/>
<p>但很可能只需显式地执行,在<a href="https://www.python.org/dev/peps/pep-0020/" rel="nofollow noreferrer">Python Zen</a>之后:</p>
<pre><code>print('hi')
print('hello'[::-1])
print('bye')
</code></pre>
<hr/>
<p>*此代码在许多情况下都不起作用,如<a href="https://stackoverflow.com/questions/49034642/decorate-any-python-function-inside-context-manager/49035013#comment85074890_49035013">the comments</a>中所述:</p>
<ul>
<li>内部函数</li>
<li>如果要修饰的函数是用<code>import x from y as z</code>导入的</li>
<li>如果您关心之后您在<code>globals()</code>中定义了一个<code>print</code>函数,而不是直接作为一个内置函数</li>
</ul>
<p>因为这更多的是一个概念的证明,是的,我们可以在这个例子中编写一个decorator,我不会试图修复这些缺点。使用我上面给出的方法,或者只使用装饰:</p>
<pre><code>print('hi')
reverse_decorator(print)('hello')
print('bye')
</code></pre>