编写文档字符串 - 指定函数参数和返回值
假设我有一个函数,比如说:
>>> def foo(a):
return a+1
我想为它编写一个文档字符串。
在文档字符串中指定它接受 a 并返回 a+1 的约定是什么?
Suppose I have a function, say:
>>> def foo(a):
return a+1
I want to write a documentation string for it.
what is the convention in specifying in the docstring that it takes a and returns a+1?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
文档字符串的想法是让用户对正在发生的事情和发生的事情有一个基本的概述,而不告诉他们太多关于这是如何发生的。在这种情况下:
对于一个不那么简单的例子,我喜欢深入了解Python关于记录函数的部分:
显然,更复杂的函数需要更大的文档字符串。只需确保文档字符串谈论的是正在发生的事情(传入的内容、返回的内容)而不是正在发生的情况(不应包含实现细节)。
The idea of a docstring is to give the user a basic overview of what's going in and coming out without telling them too much about how that happens. In this case:
For a less trivial example, I like the one in Dive Into Python's section on documenting functions:
Obviously, a more complicated function requires a bigger docstring. Just make sure the docstring is talking about what's happening (what's getting passed in, what's being returned) instead of how that's happening (implementation details should not be included).
PEP 257 应该有帮助!
PEP 257 should help!
对于 Python 约定(关于此主题和其他主题),我建议首先尝试 Python 增强建议。
Python PEP 257 建议使用一行文档字符串来指定您的函数,如下所示:
但是不是这样的:
因为后一个例子可以通过其他方式来推测。
只是浏览了一下,但 PEP 中的链接看起来可以指向其他 PEP,这些链接可以深入了解文档字符串的本质。
作为一般说明,如果您还没有浏览 PEP,我会浏览一下,因为其中有一些关于 Python 设计决策和哲学的有趣主题。
For Python conventions (about this and other topics), I'd suggest first trying the Python Enhancement Proposals.
Python PEP 257 suggests for one line docstrings to specify your function like so:
but not like this:
because the latter example can be divined through other means.
Only glanced through them but the links from the PEP look to go to other PEP's that get into the nitty-gritty of docstrings.
As a general note I'd browse through the PEPs if you haven't yet as there are some interesting topics about Python design decisions and philosophy.
我个人喜欢内置函数使用的风格。
I personally like the style the builtins use.