编写文档字符串 - 指定函数参数和返回

use*_*312 3 python docstring

假设我有一个功能,说:

>>> def foo(a):
        return a+1
Run Code Online (Sandbox Code Playgroud)

我想为它写一个文档字符串.

在docstring中指定它需要a并返回+ 1的约定是什么?

Raf*_*ler 7

文档字符串的想法是为用户提供进出的内容的基本概述,而不会过多地告诉他们如何发生这种情况.在这种情况下:

def foo(a):
    """Take a number a and return its value incremented by 1."""
    return a + 1
Run Code Online (Sandbox Code Playgroud)

对于一个不那么简单的例子,我喜欢Dive Into Python中关于记录函数的部分:

def build_connection_string(params):
    """Build a connection string from a dictionary of parameters.

    Return string."""
Run Code Online (Sandbox Code Playgroud)

显然,更复杂的功能需要更大的文档字符串.只需确保文档字符串正在讨论正在发生的事情(传递的内容,返回的内容)而不是如何发生(不应包括实现细节).