根据不同的情况,我需要导入不同的模块,例如:
if check_situation() == 1:
import helper_1 as helper
elif check_situation() == 2:
import helper_2 as helper
elif ...
...
else:
import helper_0 as helper
这些helper包含相同的字典dict01
、dict02
、dict03
……但是在不同的情况下有不同的值被调用。在
但这也有一些问题:
check_situation()
函数需要先决条件,因此它现在离顶部还很远。在那么,如何重新安排这些帮手呢?在
您可以使用
__import__()
,它接受一个字符串并返回该模块:示例:
^{pr2}$正如@wim和python3.x文档中指出的那样,
__import__()
:我自己解决,是指@Michael Scott Cuthbert
然后,如果在调用者中,我现在调用那个imp_,那么wanted,无论在调用方文件中调用还是在调用此wanted的其他文件中调用,都将被重新定向到这个或那个\u模块。在
另外,因为我只在函数中导入re-undirect,所以您不会在其他任何地方看到这个模块,而只看到想要的。在
首先,没有严格要求import语句必须位于文件的顶部,这更像是一种风格指导。在
现在,
importlib
和dict
可以用来替换你的if
/elif
链:但这只是语法上的糖,真的,我想你还有更大的事要做。听起来你需要重新考虑你的数据结构,重新设计代码。在
任何时候,只要变量名为}的容器,例如它们的列表。以数字结尾的“helper”模块名称也是如此。在
dict01
,dict02
,dict03
这是一个确定的迹象,表明你需要准备一个级别,并有一些{相关问题 更多 >
编程相关推荐