如何在另一个函数的中间实现覆盖函数调用?

时间:2018-03-11 10:54:56

标签: python import python-import

我正在编写一个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语句并立即导入所有模块。

1 个答案:

答案 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]()