单行注释
在 Python
中,使用井号 #
来标识单行注释, #
的右边内容均会被当做注释而被忽略掉。如下所示:
#!/usr/bin/python3 # 第一个注释 print ("Hello, Python!") # 第二个注释点击复制复制失败已复制
批量多行注释
多行注释可以用多个 #
号,还有 '''
和 """
,如下所示:
#!/usr/bin/python3 # 第一个注释 # 第二个注释 ''' 第三注释 第四注释 ''' """ 第五注释 第六注释 """ print ("Hello, Python!")点击复制复制失败已复制
中文注释
在使用 Python
编程时,免不了会出现或使用到中文,这时候需要在文件开头加上中文注释。
如果开头不声明保存编码的格式是什么,那么它会默认使用 ASCII
码保存文件,这时如果代码中有中文,就会报错,即使中文是在注释中的。
#coding=utf-8 or #coding=gbk点击复制复制失败已复制
文档注释
作为文档的 docstring
(文档字符串)一般出现在模块、函数和类的头部,这样在 Python
中就可以通过对象的 __doc__
属性获取文档。编辑器和 IDE
也可以根据 docstring
给出自动提示。
文档注释要遵守以下几点规范:
- 文档注释不限于中英文,但不要中英文混用
- 文档注释不是越长越好,通常一两句话能把情况说清楚即可
- 模块、共有类、共有方法,能写文档注释的,应该尽量写文档注释
模块注释
模块注释以 """
开头和结尾,首行不换行,如有多行,末行必须换行。采用 Google
的 docstring
风格。示例如下:
# -*- coding: utf-8 -*- """Example docstrings. This module demonstrates documentation as specified by the `Google Python StyleGuide`_. Docstrings may extend over multiple lines. Sections are created with a section header and a colon followed by a block of indented text. Example: Examples can be given using either the ``Example`` or ``Examples`` sections. Sections support any reStructuredText formatting, including literal blocks:: $ python example_google.py Section breaks are created by resuming unindented text. Section breaks are also implicitly created anytime a new section starts. """点击复制复制失败已复制
函数注释
不要在函数注释中复制函数原型,而是要描述具体内容,解释具体参数和返回值等,示例如下:
# 不推荐的写法(不要写函数原型) def function(a, b): """function(a, b) -> list""" …… # 正确的写法 def function(a, b): """计算并返回a到b范围内数据的平均值""" ……点击复制复制失败已复制
函数参数注释
对函数的参数、返回值等的说明采用 NumPy
标准,如下所示:
def func(arg1, arg2): """在这里写函数的一句话总结(如:计算平均值) 这里是具体描述 参数 ---------- arg1 : int arg1 的具体描述 arg2 : int arg2 的具体描述 返回值 ---------- int 返回值的具体描述 参看 ---------- otherfunc: 其他关联函数等 示例: ---------- 示例使用doctest格式,`>>>`后面的代码可以被文档测试工具作为测试用例自动运行 >>>a=[1,2,3] >>>print [x+3 for x in a] [4,5,6] """