Python: 如何在程序中更新模块
Python: How to update a module within the program
我在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中有以下代码:
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)