2016-11-08 50 views
1

此问题被标记为duplicate。但duplicate问题涉及模块,而我的问题是要求如何导入模块的部分。仅导入模块的某些部分,但将这些部分列为字符串

我知道我可以使用from mymodule import myfunction模块的某些部分import。如果要导入几件事情,但我需要将它们列为字符串。例如:

import_things = ['thing1', 'thing2', 'thing2'] 
from mymodule import import_things 

我没问this question,但它看起来像我需要使用的伎俩(如果有的话)以上为我的代码。

任何帮助表示赞赏。

回答

3
import importlib 

base_module = importlib.import_module('mymodule') 
imported_things = {thing: getattr(base_module, thing) for thing in import_things} 

imported_things['thing1']() # Function call 

如果你希望能够使用其已在全球进口的东西,然后做:

globals().update(imported_things) 
thing1() # function call 

要删除的进口,你可以做

del thing1 

del globals()['thing1'] 

另一个有用的操作可以做的是reload一个模块

+0

这个从包中导入模块。我需要能够从模块导入方法和类。 – flashburn

+0

@flashburn更新了我的答案 – smac89

+0

另一个问题。我将如何取消导入它们?有没有办法做到这一点? – flashburn