【问题标题】:How to iterate through a module's functions [duplicate]如何遍历模块的功能[重复]
【发布时间】:2014-03-20 02:20:59
【问题描述】:

我在导入 foo.py 后调用了这个函数。 Foo 有几种我需要调用的方法,例如foo.paint,foo.draw:

import foo

code

if foo:
    getattr(foo, 'paint')()

我需要使用 while 循环来调用和遍历所有函数 foo.paint、foo.draw 等。我该怎么做?

【问题讨论】:

  • 我不认为这是重复的。在那个问题中,OP 只想要信息,在这个问题中他实际上想要调用函数。

标签: python functional-programming getattr


【解决方案1】:

你可以像这样使用foo.__dict__

for name, val in foo.__dict__.iteritems(): # iterate through every module's attributes
    if callable(val):                      # check if callable (normally functions)
        val()                              # call it

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

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

[f for _, f in foo.__dict__.iteritems() if callable(f)]

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

import math
[name for name, val in math.__dict__.iteritems() if callable(val)]
['pow',
 'fsum',
 'cosh',
 'ldexp',
 ...]

【讨论】:

  • 刚接触python有点困惑如何实现这个:[f for , f in foo.__dict_.iteritems() if callable(f)]。我得到 AttributeError: 'dict' object has no attribute 'iteritems'
  • @wakamdr 看来你使用的是 Python 3,试试__dict__.items()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-13
  • 2021-11-10
  • 2016-08-17
  • 2019-08-05
  • 2016-05-04
  • 2012-08-22
相关资源
最近更新 更多