Python3 注释

单行注释、多行注释的写法,以及 Docstring 文档字符串的规范用法。

Beginner
Key Points单行用 #,多行用三引号(本质是字符串);函数/类/模块首行的三引号是 docstring,会被 __doc__ 保留。

单行注释

Everything after # to end of line is a comment and is ignored. Comment on *why*, not *what* — the code already says what it does.

Python
# 这是一个单行注释
print("Hello, World!")   # 行尾注释也可以

price = 100
tax = 0.13          # 本地税率,2024 年起生效
total = price * (1 + tax)
print(round(total, 2))

# print("这行不会执行")
print("done")
Output
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.

Python
"""
这是多行注释的常见写法。
它实际上是一个未被引用的字符串字面量。
"""

print("after block comment")

# 也可以逐行用 # 注释
# 这样更符合 PEP 8 的建议
x = 1
print(x + 1)
Output
after block comment
2

Docstring 文档字符串

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.

Python
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__)
Output
5
返回两个数的和。
True
一个极简的计算器占位类。
A docstring differs from a plain block comment by position and purpose: only a string as the first statement of a definition, not assigned to anything, lands in __doc__ and becomes extractable documentation.

Friends & Partners