我的 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/