如何调用导入的 python 模块中的每个函数

How to call every function in an imported python module

我编写了一个创建和维护数组的程序,我编写了另一个模块,该模块具有操作数组的功能。是否可以调用导入模块中的每个函数而不必对每个函数调用进行硬编码?意思是这样的:

#Some way I don't know of to get a list of function objects
    listOfFunctions = module.getAllFunctions()

    for function in listOfFunctions:
        array.function()

我想这样做,这样我就不必在每次向我的操作模块添加功能时都更新我的主文件。

我找到了这些:

How to call a function from every module in a directory in Python?

Is it possible to list all functions in a module?

listing all functions in a python module

并且也只在 python 文档的模块中找到列出函数的列表。 我可以想出一种使用一些字符串操作和 eval() 函数来执行此操作的方法,但我觉得必须有更好、更 pythonic 的方法

我想你想做这样的事情:

import inspect

listOfFunctions = [func_name for func_name, func in module.__dict__.iteritems()\
                  if inspect.isfunction(func)]

for func_name in listOfFunctions:
    array_func = getattr(array, func_name)
    array_func()

导入模块时,__dict__ 属性包含模块中定义的所有内容(变量、类、函数等)。您可以迭代它并测试该项目是否是一个函数。例如,这可以通过检查 __call__ 属性来完成:

listOfFunctions = [f for f in my_module.__dict__.values()
                   if hasattr(f,'__call__')]

然后,我们可以通过调用__call__属性来调用列表中的每个函数:

for f in listOfFunctions:
    f.__call__()

但是要小心!字典没有保证的顺序。这些函数将以某种随机顺序调用。如果顺序很重要,您可能希望使用强制执行此顺序的命名方案(fun01_do_something、fun02_do_something 等)并首先对字典的键进行排序。