DocStrings
如果模块、类或函数定义中的起始语句是字符串,那么该字符串会被视作文档字符串(DocStrings)。通过 __doc__ 属性,可直接获取文档字符的内容。help() 函数和pydoc 命令均通过获取对象的 __doc__ 属性,来提供帮助信息。
文档字符串格式要求如下:
文档字符串的缩进必须与定义中的所有其它语句保持一致。
虽然可以是 "..." 或 """...""" 字符串,但通常是"""...""" 多行字符串。
如果将 """...""" 用作文档字符串,那么第一行将被视作文档字符的标题,并以大写字母开头,同时以点号结尾;第二行是空白行;从第三行开始是详细记录程序的文档。
示例:
def print_max(x, y):
'''Prints the maximum of two numbers.
The two values must be integers.
'''
# convert to integers, if possible
x = int(x)
y = int(y)
if x > y:
print(x, 'is maximum')
else:
print(y, 'is maximum')
print_max(3, 5)
print(print_max.__doc__)
输出:
5 is maximum
Prints the maximum of two numbers.
The two values must be integers.