我可以在运行时在活动python shell中更改模块的属性吗?

我可以在运行时在活动python shell中更改模块的属性吗?,python,module,Python,Module,我可以在运行时在活动python shell中更改模块的属性吗?例如,假设我首先在终端中启动python shell。然后导入一个名为functionBundle.py的模块。假设我想使用一个函数f1,它只接受一个参数。因此,我将编写functionBundle.f1(参数)。现在,可以在运行时在活动shell中重新定义此函数了吗?例如,如果我写: def functionBundle.f1(parameter): something.... 总而言之,这能让我得到想要的结果吗?模块中

我可以在运行时在活动python shell中更改模块的属性吗?例如,假设我首先在终端中启动python shell。然后导入一个名为functionBundle.py的模块。假设我想使用一个函数f1,它只接受一个参数。因此,我将编写functionBundle.f1(参数)。现在,可以在运行时在活动shell中重新定义此函数了吗?例如,如果我写:

def functionBundle.f1(parameter):
    something....

总而言之,这能让我得到想要的结果吗?模块中的值如何?

当然,您可以使用monkeypatch模块。 假设原始
f1
是标识函数

>>> import functionBundle
>>> functionBundle.f1('returns input')
'returns input'
>>> functionBundle.f1 = lambda: 'hi'
>>> functionBundle.f1()
'hi'

是的,绝对有可能。但是,正如@Selcuk所提到的,这些变化在互动会话中是有效的

例如


如果您想在易于重用的模块中扩展或修改另一个模块的行为,请在您自己的新模块中进行

例如

mymath.py

 from math import *

 # A dumb example....
 def sqrt(x):
     return x
使用新模块的代码:

import mymath as math

# will return 10, because it calls our new,broken sqrt.
math.sqrt(10)

您可以,并且从那时起将使用您的新版本。@Selcuk那么它是否也会永久更改我的模块文件?否,它将仅在您的交互式会话期间有效。实际上,您没有修改
.py
文件。如果不修改原始模块,则无法将其永久化,但您可以编写自己的模块来包装/扩展现有模块。请参阅我的答案以获取示例。
import mymath as math

# will return 10, because it calls our new,broken sqrt.
math.sqrt(10)