循环遍历python程序中的所有方法

时间:2014-03-28 00:07:53

标签: python python-2.7 python-3.x

我想做这样的事情:

def a():
  # do stuff
  return stuff

def b():
  # do stuff
  return different_stuff

def c():
  # do one last thing
  return 200

for func in this_file:
  print func_name
  print func_return_value

我基本上想模仿这个烧瓶应用程序,没有烧瓶部分:

app = Flask(__name__)
app.register_blueprint(my_bp, url_prefix='/test')
my_bp.data = fake_data

def tests():
  with app.test_client() as c:
    for rule in app.url_map.iter_rules():
      if len(rule.arguments) == 0 and 'GET' in rule.methods:
        resp = c.get(rule.rule)
        log.debug(resp)
        log.debug(resp.data)

这可能吗?

3 个答案:

答案 0 :(得分:3)

像这样:

import sys

# some functions...
def a():
   return 'a'

def b():
   return 'b'

def c():
   return 'c'

# get the module object for this file    
module = sys.modules[__name__]

# get a list of the names that are in this module  
for name in dir(module):
   # get the Python object from this module with the given name
   obj = getattr(module, name)
   # ...and if it's callable (a function), call it.
   if callable(obj):
      print obj()

运行此命令:

bgporter@varese ~/temp:python moduleTest.py
a
b
c

请注意,这些函数不一定按照定义的顺序调用。

答案 1 :(得分:1)

也许:

def a(): return 1
def b(): return 2
def c(): return 3

for f in globals ().values ():
    if callable (f): continue
    print f.__name__
    print f ()

答案 2 :(得分:1)

使用此代码创建python模块get_module_attrs.py

import sys
module = __import__(sys.argv[1])
for name in dir(module):
   obj = getattr(module, name)
   if callable(obj):
      print obj.__name__

然后您可以将其称为$python get_module_attrs.py <name_of_module>

享受它!!