Python3 注释
单行注释、多行注释的写法,以及 Docstring 文档字符串的规范用法。
单行注释
Everything after # to end of line is a comment and is ignored. Comment on *why*, not *what* — the code already says what it does.
# 这是一个单行注释
print("Hello, World!") # 行尾注释也可以
price = 100
tax = 0.13 # 本地税率,2024 年起生效
total = price * (1 + tax)
print(round(total, 2))
# print("这行不会执行")
print("done")Hello, World!
113.0
done多行注释
Python has no dedicated multi-line comment; the convention is a triple-quoted block. Strictly it is a *string expression* that costs a little memory, and unless it sits first in a function or class it is not a docstring.
"""
这是多行注释的常见写法。
它实际上是一个未被引用的字符串字面量。
"""
print("after block comment")
# 也可以逐行用 # 注释
# 这样更符合 PEP 8 的建议
x = 1
print(x + 1)after block comment
2Docstring 文档字符串
If the first statement of a module, function or class is a string, it becomes the docstring, stored in __doc__ and shown by help(). Use triple quotes: one-line summary, blank line, then details.
def add(a, b):
"""返回两个数的和。
参数:
a: 第一个加数
b: 第二个加数
返回:
a + b 的结果
"""
return a + b
class Calc:
"""一个极简的计算器占位类。"""
print(add(2, 3))
print(add.__doc__.splitlines()[0])
print('参数' in add.__doc__)
print(Calc.__doc__)5
返回两个数的和。
True
一个极简的计算器占位类。__doc__ and becomes extractable documentation.单行注释
# 之后到行尾的内容都是注释,解释器直接忽略。注释应说明「为什么这么做」,而不是复述代码「做了什么」—— 后者读代码就知道。
# 这是一个单行注释
print("Hello, World!") # 行尾注释也可以
price = 100
tax = 0.13 # 本地税率,2024 年起生效
total = price * (1 + tax)
print(round(total, 2))
# print("这行不会执行")
print("done")Hello, World!
113.0
done多行注释
Python 没有专门的多行注释语法,惯例是用三个引号包住一段文本。注意它其实是字符串表达式,会占用一点内存;如果不在函数/类首行,也不会成为 docstring。
"""
这是多行注释的常见写法。
它实际上是一个未被引用的字符串字面量。
"""
print("after block comment")
# 也可以逐行用 # 注释
# 这样更符合 PEP 8 的建议
x = 1
print(x + 1)after block comment
2Docstring 文档字符串
模块、函数、类定义的第一条语句若是字符串,它就是 docstring,被保存在 __doc__ 里,help() 会展示它。推荐用一对三引号,首行一句话概括,空一行再写细节。
def add(a, b):
"""返回两个数的和。
参数:
a: 第一个加数
b: 第二个加数
返回:
a + b 的结果
"""
return a + b
class Calc:
"""一个极简的计算器占位类。"""
print(add(2, 3))
print(add.__doc__.splitlines()[0])
print('参数' in add.__doc__)
print(Calc.__doc__)5
返回两个数的和。
True
一个极简的计算器占位类。__doc__ 收录,成为可被工具提取的文档。