如何迭代模块的功能 [英] How to iterate through a module's functions

查看:105
本文介绍了如何迭代模块的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

导入foo.py后我有这个函数调用。 Foo有几种方法需要我打电话给foo.paint,foo.draw:

  import foo 

code

如果foo:
getattr(foo,'paint')()

我需要使用一个while循环来调用和遍历所有函数foo.paint,foo.draw等。我该如何去解决它? 解决方案

您可以像这样使用 foo .__ dict __

 如果可调用(val):#检查是否可调用(通常是函数)
val()#调用它

但请注意,这将执行模块中的每个函数(可调用)。如果某个特定函数接收到任何参数,它将失败。



获得函数的更优雅(功能性)方法是:

  [f for _,f in foo .__ dict __。iteritems()if callable(f)] 

例如,这将列出数学方法中的所有函数:

 导入数学
[name for name,val in math .__ dict __。iteritems()if callable(val)]
['pow',
'fsum',
'cosh',
'ldexp',
...]


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

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?

解决方案

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

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屋!

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