Python:如何更新程序中的模块

标签 python module

我的 Python 代码如下:

myFile = open("Test1.py", "w")
myFile.write("def foo():\n\tprint('hello world!')") #defining foo in the module Test1
myFile.close()
import Test1

Test1.foo() #this works great

myFile = open("Test1.py", "w")
#replace foo() with foo2() and a new definition
myFile.write("def foo2():\n\tprint('second hello world!')") 
myFile.close()

import Test1 #re-import to get the new functionality

Test1.foo2() #this currently throws an error since the old functionality is not replaced

我希望当我重新导入 Test1 时,foo2() 的功能取代 foo(),并且程序会打印“second hello world!”在最后。

我能找到的最佳解决方案是 "de-import"该模块看起来有潜在危险,而且似乎也没有必要(我还没有尝试过)。

将 foo2() 的新功能引入程序的最佳方法是什么?

最佳答案

您似乎想使用 reload关键字,如下所示:

>>> reload(Test1)

关于Python:如何更新程序中的模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31574002/

相关文章:

python - 二维数组与一维数组比较返回二维数组

python - pandas DataFrame 偏移列

python - Spyder/Python - 自动将工作目录设置为当前脚本的

python - 导入错误:没有名为 pymc3 的模块

ruby-on-rails - 具有相同名称的类和模块 - 如何选择一个或另一个?

javascript - Three.js 的粒子系统作为 npm 包

python - 使用 Python 分析图像亮度的方法有哪些?

python - 这个排序代码是如何工作的?

Python-导入模块导入模块

linux - 如何确定 linux 中的定时器频率