我正在编写一个Python3程序,我需要能够动态覆盖某些方法。我的文件夹结构更像是:
./
prog.py
methods/
add.py
minus.py
在prog.py
中,我想调用calc()
和add.py
中定义的minus.py
函数。我希望代码可以像以下一样工作:
def prog('foo'):
from method.foo import calc
calc()
但是在函数中间导入似乎很糟糕,可能会减慢整个程序的速度。有没有可以达到同样效果的解决方法?
我试图变得灵活,以便稍后可以添加更多方法,所以我避免使用if语句并立即导入所有模块。
答案 0 :(得分:5)
您有两个选择:
calc
属性的模块名称。calc
from ... import ... as
个功能
无论哪种方式,我都会将函数引用存储在字典中,而不是使用if .. elif
来选择一个。
第一种方法
from method import add
from method import minus
calc_functions = {
'add': add.calc,
'minus': minus.calc,
}
def prog(method):
return calc_functions[method]()
或第二个:
from method.add import calc as addition
from method.minus import calc as subtraction
calc_functions = {
'add': addition,
'minus': subtraction,
}
def prog(method):
return calc_functions[method]()
如果您需要动态导入模块,请使用importlib.import_module()
,无需担心名称冲突:
import importlib
def prog(method):
try:
calc_module = importlib.import_module('method.' + method)
except ModuleNotFoundError: # or ImportError in Python < 3.6
raise ValueError('No such method {!r}'.format(method))
return calc_module.calc()
return calc_functions[method]()