【问题标题】:List of all functions used in python program as stringpython程序中使用的所有函数的列表作为字符串
【发布时间】:2012-01-17 18:40:38
【问题描述】:

我们怎样才能找到python程序中的所有函数???例如。

输入

def func1:
  #doing something

def func2:
  #doing something

def func3:
  #doing something

输出

{'func1' , 'func2' , 'func3'}

【问题讨论】:

    标签: python string function


    【解决方案1】:

    如果你想要全局范围内的所有函数,你可以使用globals() 和inspect.isfunction():

    >>> def foo():
    ...     pass
    ... 
    >>> def bar():
    ...     pass
    ... 
    >>> import inspect
    >>> [member.__name__ for member in globals().values() \
    ...                  if inspect.isfunction(member)]
    ['bar', 'foo']
    

    【讨论】:

    • 有区别吗?当我在 line :: "for member in globals().values()" 中使用 'locals()' 而不是 'gloabals()' 时???
    • 如果你在全局范围内运行这段代码不会有任何区别,但是如果你从一个函数中运行它,区别应该会变得很明显。
    【解决方案2】:

    猜测您只需要当前上下文中的方法:

    import inspect
    
    d = locals()
    funcs = [f for f in d if inspect.isfunction(d[f])] 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      • 1970-01-01
      • 2014-05-04
      • 2022-01-01
      • 2018-10-20
      相关资源
      最近更新 更多