<p>为了详细说明<a href="https://stackoverflow.com/a/58598023/2988730">@Dan D.'s answer</a>,您需要创建一个新的函数对象来替换原来的函数对象,如下所示:</p>
<pre><code>from types import FunctionType
def reroute_decorator(**kwargs):
def actual_decorator(func):
globals = func.__globals__.copy()
globals.update(kwargs)
new_func = FunctionType(
func.__code__, globals, name=func.__name__,
argdefs=func.__defaults__, closure=func.__closure__)
new_func.__dict__.update(func.__dict__)
return new_func
return actual_decorator
</code></pre>
<p>这里唯一需要注意的是,更新后的函数对象是<em>only</em>对象,它将看到您传入的<code>kwargs</code>,因为它们将被欺骗成全局变量。另外,在调用decorator函数之后对模块所做的任何修改对decorator函数都是不可见的,但这应该不是问题。您可以再深入一层,创建一个代理字典,它允许您正常地与原始的进行交互,但您显式定义的键除外,如<code>print</code>,但这有点超出了范围。你知道吗</p>
<p>我已经将您的<code>print</code>实现更新为更一般的实现,并使decorator函数的输入更加pythonic(不太复杂):</p>
<pre><code>def my_print(*args, **kwargs):
print(*(str(x).upper() for x in args), **kwargs)
@reroute_decorator(print=my_print)
def my_func():
print('normally this print function is just a print function...')
print('but since my_func is decorated with a special reroute_decorator...')
print('it is replaced with a different function, and its args sent there.')
</code></pre>
<p>结果是:</p>
<pre><code>>>> my_func()
NORMALLY THIS PRINT FUNCTION IS JUST A PRINT FUNCTION...
BUT SINCE MY_FUNC IS DECORATED WITH A SPECIAL REROUTE_DECORATOR...
IT IS REPLACED WITH A DIFFERENT FUNCTION, AND ITS ARGS SENT THERE.
</code></pre>