如何在导入的python模块中调用每个函数 [英] How to call every function in an imported python module

查看:54
本文介绍了如何在导入的python模块中调用每个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个编写的程序来创建和维护数组,还有另一个我编写的模块具有处理该数组的功能.是否可以在不对每个函数调用进行硬编码的情况下调用导入模块中的每个函数?意思是这样的:

I have a program that I wrote that is creating and maintaining an array and I have another module that I wrote that has functions to manipulate the array. Is it possible to call every function in the imported module without having to hard code every function call? Meaning something like this:

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

    for function in listOfFunctions:
        array.function()

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

I want to do this so I don't have to update my main file every time I add a function to my manipulation module.

我发现了这些:

如何调用python目录中每个模块的功能?

可以在一个列表中列出所有功能模块?

列出python模块中的所有函数

,还仅在python文档上的模块中找到列出的功能.我可以想到一种使用一些字符串操作和 eval()函数的方法,但是我觉得必须有一种更好,更pythonic的方法

and also only found listing the functions in a module on the python docs. I can think of a way to do this using some string manipulation and the eval() function but I feel like there has to be a better, more pythonic way

推荐答案

我认为您想执行以下操作:

I think you want to do something like this:

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()

这篇关于如何在导入的python模块中调用每个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆