假设我有两个模块:
a.py
我的目标是在b中使用
下面是一个示例:
目前的结果是
我想到了两种复杂的方法可以解决这个问题,但我对它们都不满意:
a.py
value = 3
def x()
return value
b.py
from a import x
value = 4
我的目标是在b中使用
a.x
的功能,但更改函数返回的值。具体来说,在运行b.x()
时,将使用a
作为全局名称源查找value
。我基本上正在尝试创建一个与a.x
完全相同的函数对象副本,但它使用b来获取其全局变量。有没有一个相当简单的方法来做到这一点?下面是一个示例:
import a, b
print(a.x(), b.x())
目前的结果是
3 3
,但我希望它是3 4
。我想到了两种复杂的方法可以解决这个问题,但我对它们都不满意:
- Re-define
x
in moduleb
using copy-and paste. The real function is much more complex than shown, so this doesn't sit right with me. Define a parameter that can be passed in to x and just use the module's value:
def x(value): return value
This adds a burden on the user that I want to avoid, and does not really solve the problem.
a.value
来访问它。我不知道你为什么提到函数x()
。 - llllllllll