如果我想将模块作为字符串导入,如何使用 from import?

How to use from import if I would like to import the module as a String?

我有一个数组中的模块名称列表。 我想从已导入的 class 中导入所有这些模块。 似乎我无法使用 from TestModule __import__(name)

我该怎么做?这是我拥有的:

import MainModule
arr = \
    ['Module1', 'Module2', 'Module3', 'Module4', 'Module5']
for string in arr:
     # Use FROM  to import the sub classes somehow
     from MainModule __import__(string)

当然Python不允许我那样做。

import MainModule
arr = \
    ['Module1', 'Module2', 'Module3', 'Module4', 'Module5']
for string in arr:
    globals()[string] = getattr(MainModule, string)

可能对你有帮助,虽然修改 globals() 不是很优雅。

更好

modules = {string: getattr(MainModule, string) for string in arr}

然后用 modules 做任何你想做的事,e。 g.

class MyModulesHolder(dict):
    pass

modules = MyModulesHolder()
modules.__dict__ = modules
modules.update({string: getattr(MainModule, string) for string in arr})

这样你就可以modules.Module2.whatever().