如何遍历模块的函数 [英] How to iterate through a module's functions
问题描述
我在导入 foo.py 后调用了这个函数.Foo 有几个我需要调用的方法,例如foo.paint, foo.draw:
I have this function call after importing foo.py. Foo has several methods that I need to call e.g. foo.paint, foo.draw:
import foo
code
if foo:
getattr(foo, 'paint')()
我需要使用 while 循环来调用和迭代所有函数 foo.paint、foo.draw 等.我该怎么做?
I need to use a while loop to call and iterate through all the functions foo.paint, foo.draw etc. How do i go about it?
推荐答案
你可以像这样使用 foo.__dict__
:
You can use foo.__dict__
somehow like this:
for name, val in foo.__dict__.iteritems(): # iterate through every module's attributes
if callable(val): # check if callable (normally functions)
val() # call it
但请注意,这将执行模块中的每个函数(可调用).如果某个特定函数接收到任何参数,它将失败.
But watch out, this will execute every function (callable) in the module. If some specific function receives any arguments it will fail.
一种更优雅的(函数式)获取函数的方法是:
A more elegant (functional) way to get functions would be:
[f for _, f in foo.__dict__.iteritems() if callable(f)]
例如,这将列出 math
方法中的所有函数:
For example, this will list all functions in the math
method:
import math
[name for name, val in math.__dict__.iteritems() if callable(val)]
['pow',
'fsum',
'cosh',
'ldexp',
...]
这篇关于如何遍历模块的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!