覆盖使用 from...import 的模块方法 [英] Override module method where from...import is used
问题描述
我无法覆盖使用 from...import 语句的方法.一些说明问题的例子:
I have problem to override method where from...import statement is used. Some example to illustrate the problem:
# a.py module
def print_message(msg):
print(msg)
# b.py module
from a import print_message
def execute():
print_message("Hello")
# c.py module which will be executed
import b
b.execute()
我想在不更改 a 或 b 模块中的代码的情况下覆盖 print_message(msg) 方法.我尝试了很多方法,但是 from...import 导入原始方法.当我将代码更改为
I'd like to override print_message(msg) method without changing code in a or b module. I tried in many ways but from...import imports original method. When I changed code to
import a
a.print_message
比我看到我的变化.
你能建议我如何解决这个问题吗?
在此先感谢您提供的任何小示例.
Could you suggest my how to solve this problem?
Thanks in advance for any little example.
最好的问候
------------------- 更新-------------------
我试着像下面那样做,例如:
------------------ Update ------------------
I tried to do that like below e.g.:
# c.py module
import b
import a
import sys
def new_print_message(msg):
print("New content")
module = sys.modules["a"]
module.print_message = new_print_message
sys.module["a"] = module
但这在我使用 for...import 语句的地方不起作用.仅适用于导入 a,但正如我所写,我不想更改 b.py 和 a.py 模块中的代码.
But this is not working where I'm using for...import statement. Is working only for import a but as I wrote I don't want change code in b.py and a.py modules.
推荐答案
保持 a
和 b
模块不变,你可以尝试实现 c
如下:
With your a
and b
modules untouched you could try implementing c
as follows:
import a
def _new_print_message(message):
print "NEW:", message
a.print_message = _new_print_message
import b
b.execute()
您必须首先导入 a
,然后覆盖该函数,然后导入 b
以便它使用已经存在的 a
模块导入(并更改).
You have to first import a
, then override the function and then import b
so that it would use the a
module that is already imported (and changed).
这篇关于覆盖使用 from...import 的模块方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!