【问题标题】:How to see function signature in Python?如何在 Python 中查看函数签名?
【发布时间】:2011-05-24 02:52:16
【问题描述】:

有没有办法自省一个函数,以便它向我显示它所接受的参数的信息(如参数的数量、可能的类型、如果命名的参数名称)和返回值? dir() 似乎没有做我想做的事。 __doc__ 字符串有时包含方法/函数参数,但通常不包含。

【问题讨论】:

  • 一般来说,文档(不一定是__doc__你最好的选择。
  • 查看函数签名。步骤 1. 阅读代码。步骤 2. 搜索。 stackoverflow.com/questions/2677185/how-read-method-signature这里已经回答了好几次了。 stackoverflow.com/questions/3375573/…,也是。
  • 欣赏链接,但老实说,我认为我的问题比您转发的问题更简洁明了。至少证明了这一点,因为我确实进行了搜索,但在搜索了几分钟后它没有出现任何内容。 :\
  • @mindthief:有趣的是,您接受的答案与您的要求完全不一致。您在问题中明确拒绝了 __doc__ 字符串,但在回答中接受了它。从那以及你的 cmets 不清楚你真正在寻找什么。你能详细说明一下吗?
  • @S.Lott 当然,__doc__仅显示函数的文档字符串,而不是参数。如果幸运的话,文档字符串可能会解释参数的使用并隐含地提供我正在寻找的信息。但是 help() 函数为您提供了确切的函数签名(这是我声明的要求)以及 doc 字符串,这确实是您需要的一切,因为 doc 字符串可能包含仅从签名中不明显的额外解释。答案示例实际上是在类而不是函数上调用的,这就是为什么它看起来比您预期的更冗长。

标签: python introspection


【解决方案1】:

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

【讨论】:

  • 工作就像一个魅力,谢谢!来自相关问题的其他解决方案也适用:import inspect print(inspect.getargspec(the_function)) 但 help() 更好!
  • 我已经使用python 5 年多了,但我不知道那个。太棒了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-12
  • 1970-01-01
  • 1970-01-01
  • 2010-11-27
  • 1970-01-01
  • 2011-04-01
  • 2021-01-08
相关资源
最近更新 更多