且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python 模块的动态加载

更新时间:2023-12-05 08:51:58

我不确定失败"是什么意思,所以我只提一下 __import__('structures.index') 事实上,应该可以工作,但它不会在当前范围内分配模块名称.要做到这一点(然后在动态导入的模块中使用一个类),您必须使用:

I'm not sure what "it fails" means, so I'll just mention that __import__('structures.index') should, in fact, work, but it doesn't assign the module name in the current scope. To do that (and then use a class in the dynamically imported module), you'll have to use:

structures = __import__('structures.index')
structures.index.SomeClass(...)

__import__ 的完整详细信息可在这里获得.

The complete details on __import__ are available here.

(基于问题编辑)

要导入 neoform.structures.index,并返回 index 模块,您需要执行以下操作:

To import neoform.structures.index, and return the index module, you would do the following:

structures = __import__('neoform.structures.index', 
                        fromlist=['does not in fact matter what goes here!'])

因此,如果您有一个包名称列表 packages,您可以导入它们的 index 模块并使用以下代码:

So if you have a list of package names packages, you can import their index modules and instantiate some MyClass class for each using the following code:

modules = [ __import__('neoform.%s.index' % pkg, fromlist=['a']) 
            for pkg in packages ]
objects = [ m.MyClass() for m in modules ]