Skip to main content
 首页 » 编程设计

python之我可以在运行时在事件的 python shell 中更改模块的属性吗

2024年10月24日9lyhabc

我可以在运行时在事件的 python shell 中更改模块的属性吗?例如,假设我首先在我的终端中启动一个 python shell。然后我导入一个名为 functionBundle.py 的模块。假设我想使用某个函数 f1,它只需要一个参数。所以我会写 functionBundle.f1(parameter)。现在,是否可以在运行时在事件 shell 中重新定义此函数?例如,如果我写:

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

在 shell 中,这会得到我想要的结果吗?模块中的值如何?

请您参考如下方法:

是的,这绝对有可能。但正如@Selcuk 所提到的,这些更改对该交互式 session 有效。

例如。

## myModule.py 
def printHello(): 
   print "hello" 
 
## otherModule 
import myModule 
print myModule.printHello()  ## prints hello 
 
def otherPrint(): 
   print "Hello world" 
 
myModule.printHello = otherPrint 
myModule.printHello()  ## prints Hello world