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

时间:2015-07-22 21:07:55

标签: 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(),程序将打印“第二个hello world!”最后。

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

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

1 个答案:

答案 0 :(得分:2)

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

>>> reload(Test1)