如何查看Python中的函数签名?

14 投票
1 回答
9311 浏览
提问于 2025-04-16 08:24

有没有办法查看一个函数的信息,比如它需要多少个参数、参数的类型(如果可能的话)、参数的名字(如果有命名的话)以及它返回的值是什么?使用 dir() 似乎不能满足我的需求。虽然 __doc__ 字符串有时候会包含方法或函数的参数信息,但很多时候却没有。

1 个回答

20

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

撰写回答