如何在Python中看到函数签名?

min*_*ief 11 python introspection

有没有一种方法来反思了一项功能,它显示我的需要(如参数的个数数量,类型,如果可能的,如果命名的参数名称)和返回值参数的信息?dir()似乎没有做我想要的.该__doc__字符串有时包括方法/函数的参数,但往往并非如此.

Joc*_*zel 17

help(the_funcion) 应该给你所有的信息.

样品:

>>> help(enumerate)
Help on class enumerate in module __builtin__:

class enumerate(object)
 |  enumerate(iterable[, start]) -> iterator for index, value of iterable
 |
 |  Return an enumerate object.  iterable must be another object that supports
 |  iteration.  The enumerate object yields pairs containing a count (from
 |  start, which defaults to zero) and a value yielded by the iterable argument
 |  enumerate is useful for obtaining an indexed list:
 |      (0, seq[0]), (1, seq[1]), (2, seq[2]), ...
 |
 |  Methods defined here:
 |
 |  __getattribute__(...)
 |      x.__getattribute__('name') <==> x.name
 |
 |  __iter__(...)
 |      x.__iter__() <==> iter(x)
 |
 |  next(...)
 |      x.next() -> the next value, or raise StopIteration
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __new__ = <built-in method __new__ of type object>
 |      T.__new__(S, ...) -> a new object with type S, a subtype of T
Run Code Online (Sandbox Code Playgroud)

  • 工作就像一个魅力,谢谢!来自相关问题的另一个解决方案也有效:`import inspect print(inspect.getargspec(the_function))`但是help()要好得多! (4认同)