35

我在覆盖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()

我想覆盖print_message(msg)方法而不更改 a 或 b 模块中的代码。我尝试了很多方法,但from...import导入了原始方法。当我将代码更改为

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语句的地方不起作用。仅适用于 import a 但正如我所写,我不想更改 b.py 和 a.py 模块中的代码。

4

2 回答 2

58

在您的ab模块不变的情况下,您可以尝试c如下实现:

import a

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

a.print_message = _new_print_message

import b
b.execute()

您必须首先 import a,然后覆盖该函数,然后 importb以便它使用a已导入(并更改)的模块。

于 2012-05-31T07:44:47.773 回答
0

模块1.py

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

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

模块2.py

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
"""
于 2021-06-08T06:45:12.807 回答