前言
说起注释大家肯定都不会陌生,各种教程中也提到了 python 注释的方法,其中很多教程都说到了 python 的多行注释,关于多行注释,他们经常说,使用 """ """ 或者 ''' ''',然而遗憾的是,python 中并不存在多行注释. 为什么这么说,让我们一起看一下 python PEP8 编码规范中的关于注释的部分.
规范中提及的注释分为三种,依次是 Block Comments, Inline Comments, Documentation Strings,接下来让我们详细了解一下.
Block Comments
原文:
Block comments generally apply to some (or all) code that follows them, and are indented to the same level as that code. Each line of a block comment starts with a # and a single space (unless it is indented text inside the comment).
Paragraphs inside a block comment are separated by a line containing a single #.
翻译:
块注释通常适用于跟随它们的一些(或所有)代码,并且缩进到与该代码相同的级别。块注释的每一行都以#和单个空格开头(除非它是注释中的缩进文本)。
块注释中的段落由包含单个#的行分隔
Inline Comments
原文:
Use inline comments sparingly.
An inline comment is a comment on the same line as a statement. Inline comments should be separated by at least two spaces from the statement. They should start with a # and a single space.
Inline comments are unnecessary and in fact distracting if they state the obvious. Don't do this:
x = x + 1 # Increment x
But sometimes, this is useful:
x = x + 1 # Compensate for border
翻译:
尽可能少使用行内注释。
行内注释是与代码语句同行的注释。行内注释和代码至少要有两个空格分隔。注释由 # 和一个空格开始。
事实上,如果状态明显的话,行内注释是不必要的,反而会分散注意力。比如说下面这样就不需要:
但有时,这很有用:
Documentation Strings
原文:
Conventions for writing good documentation strings (a.k.a. "docstrings") are immortalized in PEP 257.
Write docstrings for all public modules, functions, classes, and methods. Docstrings are not necessary for non-public methods, but you should have a comment that describes what the method does. This comment should appear after the def line.
PEP 257 describes good docstring conventions. Note that most importantly, the """ that ends a multiline docstring should be on a line by itself:
"""Return a foobang
Optional plotz says to frobnicate the bizbaz first.
"""
For one liner docstrings, please keep the closing """ on the same line.
翻译:
为所有公共模块、函数、类和方法编写文档字符串。对于非公共方法,docstrings 不是必需的,但是应该有一个注释来描述该方法的功能。这个注释应该出现在 def 行之后。
PEP 257描述了良好的文档字符串约定。注意,最重要的是,结束多行文档字符串的 """ 应该单独在一行上:
对于一行 docstrings,请保持关闭 """ 在同一行。
结论
pep8 中关于注释提提及的唯一注释方法就是使用#字符串去注释, 并没有提及用 """ 或者 ''' 作为多行注释使用,不过 python 的创造者对此也说了一句话:
Python tip: You can use multi-line strings as multi-line comments. Unless used as docstrings, they generate no code! :-)
领取专属 10元无门槛券
私享最新 技术干货