Calling a function of a module from a string with the function's name in Python向我们展示了如何使用getattr(“ bar ”)()来调用函数,但这假设我们已经导入了模块 foo .
假如我们可能还必须执行 foo (或 bar import foo )的导入,那么我们将如何调用 "foo.bar" 的执行呢?
Calling a function of a module from a string with the function's name in Python向我们展示了如何使用getattr(“ bar ”)()来调用函数,但这假设我们已经导入了模块 foo .
假如我们可能还必须执行 foo (或 bar import foo )的导入,那么我们将如何调用 "foo.bar" 的执行呢?
4 回答
使用
__import__(....)
函数:http://docs.python.org/library/functions.html#import
(David几乎拥有它,但我认为如果你想重新定义正常的导入过程,例如从zip文件加载,他的例子更适合做什么)
您可以使用imp模块中的
find_module
和load_module
来加载在执行时确定其名称和/或位置的模块 .文档主题末尾的示例说明了如何:
这是我最终想出的功能,以便从虚线名称中获取我想要的功能
这个解决方案不起作用? Calling a function of a module from a string with the function's name in Python