I am trying to learn how Python reloads modules, but have hit a roadblock. Let's say I have:
我正在尝试学习Python如何重新加载模块,但遇到了障碍。比方说我有:
dir1\file1.py
:
from dir2.file2 import ClassOne
myObject = ClassOne()
dir1\dir2\file2.py
:
class ClassOne():
def reload_module():
reload(file2)
The reload call fails to find module "file2".
重新加载调用无法找到模块“file2”。
My question is, how do I do this properly, without having to keep everything in one file?
我的问题是,如何正确地做到这一点,而不必将所有内容保存在一个文件中?
A related question: When the reload does work, will myObject use the new code?
一个相关的问题:当重新加载确实有效时,myObject会使用新代码吗?
thank you
1 个解决方案
#1
def reload_module():
import file2
reload(file2)
However, this will not per se change the type of objects you've instantiated from classes held in the previous version of file2. The Python Cookbook 2nd edition has a recipe on how to accomplish such feats, and it's far too long and complex in both code and discussion to reproduce here (I believe you can read it on google book search, or failing that the original "raw" version [before all the enhancements we did to it], at least, should still be on the activestate cookbook online site).
但是,这本身不会更改您从先前版本的file2中保存的类中实例化的对象类型。 Python Cookbook第2版有一个关于如何完成这些专长的方法,它在代码和讨论中都太长而复杂,无法在这里重现(我相信你可以在google book search上阅读它,或者说原来的“raw”没有版本[在我们对它做的所有增强之前],至少应该仍然在activestate cookbook在线网站上)。
#1
def reload_module():
import file2
reload(file2)
However, this will not per se change the type of objects you've instantiated from classes held in the previous version of file2. The Python Cookbook 2nd edition has a recipe on how to accomplish such feats, and it's far too long and complex in both code and discussion to reproduce here (I believe you can read it on google book search, or failing that the original "raw" version [before all the enhancements we did to it], at least, should still be on the activestate cookbook online site).
但是,这本身不会更改您从先前版本的file2中保存的类中实例化的对象类型。 Python Cookbook第2版有一个关于如何完成这些专长的方法,它在代码和讨论中都太长而复杂,无法在这里重现(我相信你可以在google book search上阅读它,或者说原来的“raw”没有版本[在我们对它做的所有增强之前],至少应该仍然在activestate cookbook在线网站上)。