A function definition will often include documentation describing the function, called a docstring, which must be indented along with the function body. Docstrings are conventionally triple quoted. The first line describes the job of the function in one line. The following lines can describe arguments and clarify the behavior of the function:
函数定义通常包含描述函数的文档,称为 docstring,必须与函数体一起缩进。文档字符串通常是三重引号。第一行用一行描述了函数的工作。下面的行可以描述参数并阐明函数的行为:
>>> def pressure(v, t, n):
"""Compute the pressure in pascals of an ideal gas.
Applies the ideal gas law: http://en.wikipedia.org/wiki/Ideal_gas_law
v -- volume of gas, in cubic meters
t -- absolute temperature in degrees kelvin
n -- particles of gas
"""
k = 1.38e-23 # Boltzmann's constant
return n * k * t / v
When you call help with the name of a function as an argument, you see its docstring (type q to quit Python help).
当你以函数名称作为参数来调用help时,你会看到它的文档字符串(按下q来退出 Python 帮助)。
>>> help(pressure)
When writing Python programs, include docstrings for all but the simplest functions. Remember, code is written only once, but often read many times. The Python docs include docstring guidelines that maintain consistency across different Python projects.
Comments. Comments in Python can be attached to the end of a line following the # symbol. For example, the comment Boltzmann’s constant above describes k. These comments don’t ever appear in Python’s help, and they are ignored by the interpreter. They exist for humans alone.
在编写 python 程序时,除了最简单的函数之外,所有函数都包含 docstring。记住,代码只写一次,但通常要读很多遍。Python 文档包含文档字符串指南,可以在不同的 python 项目中保持一致性。Python 中的注释可以附加到 # 符号后面的一行末尾。例如,上面的 boltzmann’s constant 描述了 k,这些注释在 python 的帮助中从未出现过,它们被解释器忽略了。它们只为人类而存在。