代码之家  ›  专栏  ›  技术社区  ›  oneself

用Python打印出函数参数列表

  •  4
  • oneself  · 技术社区  · 16 年前

    有没有办法打印出函数的参数列表? 例如:

    def func(a, b, c):
      pass
    
    print_func_parametes(func)
    

    这将产生如下结果:

    ["a", "b", "c"]
    
    3 回复  |  直到 16 年前
        1
  •  17
  •   Dzinx    16 年前

    使用检查模块。

    >>> import inspect
    >>> inspect.getargspec(func)
    (['a', 'b', 'c'], None, None, None)
    

    返回的元组的第一部分就是您要查找的内容。

        2
  •  6
  •   S.Lott    16 年前

        3
  •  2
  •   Noah    16 年前

    你也可以试试内置的 help() 函数,它不仅提供命名参数的列表,还提供 func() 如果您提供了docstring:

    >>> def func(a, b, c):
    ...     """do x to a,b,c and return the result"""
    ...     pass
    ... 
    >>> help(func)
    

        
    Help on function func in module __main__:
    
    func(a, b, c)
        do x to a,b,c and return the result
    

    大多数模块至少提供了某种内置文档。