1: 单行、行内和多行注释
当基本代码本身不清楚时,注释用来解释该代码块实现什么功能做什么事情。
Python 解释器会忽略注释,因此不会执行注释中的代码,也不会对注释中的普通英语句子提出语法错误。
单行注释以散列字符 (#) 开始,以行结束符结束。
单行注释:
# This is a single line comment in Python
行内注释:
print("Hello World") # This line prints "Hello World"
跨多行的注释两端有"""或'''。这与多行字符串相同,但它们可以用作注释:
"""
This type of comment spans multiple lines.
These are mostly used for documentation of functions, classes and modules.
"""
2: 以编程方式访问文档字符串
与普通注释不同,Docstrings 是作为其记录的函数的属性存储的,这意味着您可以通过编程访问它们。
一个示例函数
def func():
"""This is a function that does nothing at all"""
return
可以使用 __doc__ 属性访问 docstring:
print(func.__doc__)
这是一个什么都不做的函数
help(func)
关于模块 __main__ 中函数 func 的帮助:
func()
This is a function that does nothing at all
另一个函数示例
function.__doc__ 只是实际的 docstring 字符串,而 help 函数提供关于函数的一般信息,包括 docstring。下面是一个更有用的例子:
def greet(name, greeting="Hello"):
"""Print a greeting to the user `name`
Optional parameter `greeting` can change what they're greeted with."""
print("{} {}".format(greeting, name))
help(greet)
关于模块 __main__ 中函数 greet 的帮助:
greet(name, greeting='Hello')
Print a greeting to the user name
Optional parameter greeting can change what they're greeted with.
文档字符串比普通注释的优势
在函数中不加文档字符串或普通注释会使函数的作用大打折扣。
def greet(name, greeting="Hello"):
# Print a greeting to the user `name`
# Optional parameter `greeting` can change what they're greeted with.
print("{} {}".format(greeting, name))
print(greet.__doc__)
None
help(greet)
关于模块 __main__ 中函数问候语的帮助:
greet(name, greeting='Hello')
3: 使用 docstrings 编写文档
docstring 是多行注释,用于记录模块、类、函数和方法。它必须是所描述组件的第一条语句。
def hello(name):
"""Greet someone.
Print a greeting ("Hello") for the person with the given name.
"""
print("Hello "+name)
class Greeter:
"""An object used to greet people.
It contains multiple greeting functions for several languages
and times of the day.
"""
docstring 的值可以在程序中访问,例如,帮助命令就使用了 docstring 的值。
语法约定
PEP 257
PEP 257 定义了文档字符串注释的语法标准。它基本上允许两种类型:
单行文档字符串:
根据 PEP 257,单行文档应该用于简短的函数。所有内容都放在一行中,例如
def hello():
"""Say hello to your friends."""
print("Hello my friends!")
文档字符串应以句号结束,动词应为谓语形式。
多行文档字符串:
对于较长、较复杂的函数、模块或类,应使用多行文档字符串。
def hello(name, language="en"):
"""Say hello to a person.
Arguments:
name: the name of the person
language: the language in which the person should be greeted
"""
print(greeting[language]+" "+name)
它们以简短的摘要(相当于单行 docstring 的内容)开始,摘要可以与引号在同一行,也可以在下一行,并给出额外的细节,列出参数和返回值。
请注意,PEP 257 定义了文档字符串中应提供哪些信息,但并未定义提供信息的格式。这也是其他各方和文档解析工具指定自己的文档标准的原因,下面和本问题中列出了其中一些标准。
Sphinx
Sphinx 是一个基于 docstrings 为 Python 项目生成 HTML 文档的工具。它使用的标记语言是 reStructuredText。他们定义了自己的文档标准,pythonhosted.org 对这些标准有很好的描述。例如,pyCharm IDE 就使用了 Sphinx 格式。
使用 Sphinx/reStructuredText 格式的函数文档如下:
def hello(name, language="en"):
"""Say hello to a person.
:param name: the name of the person
:type name: str
:param language: the language in which the person should be greeted
:type language: str
:return: a number
:rtype: int
"""
print(greeting[language]+" "+name)
return 4
谷歌 Python 风格指南
Google 发布了《Google Python 风格指南》,定义了 Python 的编码规范,包括文档注释。与 Sphinx/reST 相比,许多人认为根据 Google 指南编写的文档更易于人类阅读。
上文提到的 pythonhosted.org 页面也提供了一些根据《Google Python 风格指南》编写文档的范例。
使用 Napoleon 插件,Sphinx 也能以符合《Google Python 风格指南》的格式解析文档。
使用《Google Python 风格指南》格式的函数文档如下所示:
def hello(name, language="en"):
"""Say hello to a person.
Args:
name: the name of the person as string
language: the language code string
Returns:
A number.
"""
print(greeting[language]+" "+name)
return 4