Python:如何两次加载一个模块? [英] Python: How to load a module twice?

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

问题描述

是否可以在同一python会话中两次加载一个模块?
用一个例子填补这个问题:这是一个模块:

Is there a way to load a module twice in the same python session?
To fill this question with an example: Here is a module:

Mod.py

x = 0

现在,我想两次导入该模块,例如创建一个类的两个实例以实际上具有两个x副本.

Now I would like to import that module twice, like creating two instances of a class to have actually two copies of x.

要已经回答注释中的问题,为什么只要创建一个以x作为变量的类,为什么有人会想这样做呢?":
您是正确的,但是存在大量必须重写的源,并且两次加载模块将是一个快速解决方案^^.

To already answer the questions in the comments, "why anyone would want to do that if they could just create a class with x as a variable":
You are correct, but there exists some huge amount of source that would have to be rewritten, and loading a module twice would be a quick fix^^.

推荐答案

是的,您可以加载一个模块两次:

Yes, you can load a module twice:

import mod
import sys
del sys.modules["mod"]
import mod as mod2

现在,modmod2是同一模块的两个实例.

Now, mod and mod2 are two instances of the same module.

也就是说,我怀疑这是否有用.改用类-最终将减少工作量.

That said, I doubt this is ever useful. Use classes instead -- eventually it will be less work.

编辑:在Python 2.x中,您还可以使用以下代码手动"导入模块:

Edit: In Python 2.x, you can also use the following code to "manually" import a module:

import imp

def my_import(name):
    file, pathname, description = imp.find_module(name)
    code = compile(file.read(), pathname, "exec", dont_inherit=True)
    file.close()
    module = imp.new_module(name)
    exec code in module.__dict__
    return module

此解决方案可能比第一个更灵活.您不再需要与之抗争"导入机制,因为(部分)滚动了自己的导入机制. (请注意,此实现不会设置模块的__file____path____package__属性-如果需要这些属性,只需添加代码进行设置即可.)

This solution might be more flexible than the first one. You no longer have to "fight" the import mechanism since you are (partly) rolling your own one. (Note that this implementation doesn't set the __file__, __path__ and __package__ attributes of the module -- if these are needed, just add code to set them.)

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

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