如何重新加载导入另一个文件的Python模块? [英] How to reload a Python module that was imported in another file?

查看:211
本文介绍了如何重新加载导入另一个文件的Python模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习Python如何重新加载模块,但遇到了障碍。
假设我有:

I am trying to learn how Python reloads modules, but have hit a roadblock. Let's say I have:

dir1 \ file1.py

from dir2.file2 import ClassOne
myObject = ClassOne()

dir1 \dir2\file2.py

class ClassOne():
   def reload_module():
       reload(file2)

重新加载调用无法找到模块file2。

The reload call fails to find module "file2".

我的问题是,我该如何正确地做到这一点,而不必将所有内容保存在一个文件中?

My question is, how do I do this properly, without having to keep everything in one file?

相关问题:当​​重新加载确实有效时,myObject会使用新代码吗?

A related question: When the reload does work, will myObject use the new code?

谢谢

推荐答案

   def reload_module():
       import file2
       reload(file2)

然而,这将每se更改您从file2的早期版本中保存的类中实例化的对象类型。 Python Cookbook第2版有一个关于如何完成这些专长的方法,并且在代码和讨论中复制过程太长而复杂(我相信你可以在谷歌图书搜索中阅读它,或者说原来的原始失败了版本[在我们对它做的所有增强之前],至少应该仍然在activestate cookbook在线网站上。)

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).

这篇关于如何重新加载导入另一个文件的Python模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆