如何打印 Python 函数需要/允许哪些参数?
假设我有一个函数,我想打印出它接受的参数。我该怎么做?
Suppose I have a function and I want to print out the arguments it accepts. How can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用
inspect.getargspec()
查找出去。Use
inspect.getargspec()
to find out.我看到有人已经给出了我想要的答案,所以我会建议一个纯粹实用的答案。 IDLE 将为您提供函数的参数作为“工具提示”。
默认情况下应启用此功能;在您键入函数名称和左括号后,工具提示将立即出现。
为此,IDLE 只需访问函数的文档字符串,因此它将显示任何 Python 函数的工具提示——标准库、第三方库,甚至是您之前创建的且位于 IDLE 可访问的命名空间中的函数。
显然,这仅当您在 IDLE 中以交互模式工作时才有效,尽管它确实具有不需要额外函数调用的优点。
I see that someone has already offered the answer i had in mind, so i'll suggest a purely practical one. IDLE will give you a function's parameters as a 'tooltip'.
This should be enabled by default; the tooltip will appear just after you type the function name and the left parenthesis.
To do this, IDLE just accesses the function's doc string, so it will show the tooltip for any python function--standard library, third-party library, or even a function you've created earlier and is in a namespace accessible to IDLE.
Obviously, this is works only when you are working in interactive mode in IDLE, though it does have the advantage of not requiring an additional function call.
help
函数可以执行此操作。您所要做的就是为您的函数放入文档字符串。
The
help
function does this.All you have to do is put in docstrings for your functions.
如果您使用 IPython(您绝对应该这样做),请使用
查看文档,包括函数期望的内容,并且:
查看上述文档以及源代码(如果有)
if you use IPython (as you absolutely should), use
to see the documentation, including what the function expects, and:
to see the above documentation plus the source code (if available)