Python 重写使用“从…导入”的模块方法

Python 重写使用“从…导入”的模块方法,python,Python,我无法重写使用from…import语句的方法。举例说明问题: # 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模块中的代码的情况下

我无法重写使用from…import语句的方法。举例说明问题:

# 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)方法。我尝试了很多方法,但从…导入原始方法。当我把代码改成

import a
a.print_message
比我看到我的零钱

你能建议我如何解决这个问题吗?
提前感谢您提供的任何小示例

致意

------------------更新-----------------
我试着像下面这样做,例如:

# 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模块中的代码。

如果未触及
a
b
模块,您可以尝试实现
c
,如下所示:

import a

def _new_print_message(message):
    print "NEW:", message

a.print_message = _new_print_message

import b
b.execute()
您必须首先导入
a
,然后重写该函数,然后导入
b
,以便它使用已导入(并更改)的
a
模块

模块1.py 模块2.py
(1) 你说的“覆盖”到底是什么意思?猴子补丁?(2) 在您显示的代码中,只有一个
print\u message()
。我想将print\u message()方法更改为打印,例如“New content”消息。如何在不改变a.py和b.py的情况下从c.py文件实现这一点?对于“猴子补丁”的解释和演示:您的代码正在工作。我的错误是在覆盖print_message方法之前放了import b语句。在a.print\u message=\u new\u print\u message代码运行后使用import b。感谢您的帮助。PEP-8建议将所有导入语句放在模块顶部。这与在.CPP文件中间有一个包含语句相同;你最终会陷入痛苦的世界。
def function1():
    print("module1 function1")
    function2()

def function2():
    print("module1 function2")
import module1

test = module1.function1()
print(test) 

""" output
module1 function1
module1 function2
"""
def myfunction():
    print("module2 myfunction")

module1.function2 = lambda: myfunction()

test = module1.function1()
print(test)

"""output
module1 function1
module2 myfunction
"""