Docstring
一句话解释
docstring 是 字符串 literal as 首先 语句 in 模块, 函数, or 类, used for documentation.
用大白话说
docstring (documentation 字符串) 是字符串 literal 那个 appears as 首先语句 in 模块, 函数, 类, or 方法. 它 documents 什么 code 做. 通过约定, use 三 quotes ("""...""").
Docstrings are accessible at runtime via the __doc__ attribute and are used by tools like help(), Sphinx, and IDEs to generate documentation. They are the Pythonic way to document code.
A good docstring describes what the function does, its parameters, return value, and any exceptions it might raise. Follow a style guide like Google, NumPy, or reStructuredText format for consistency.
示例
def divide(a, b):
"""Divide a by b and return the result.
Args:
a: The numerator.
b: The denominator (must not be zero).
Returns:
The quotient a / b.
Raises:
ZeroDivisionError: If b is zero.
"""
return a / b
print(divide.__doc__)
help(divide)Docstrings 是 三-quoted 字符串 documenting code. Access 通过 __doc__ or help().
常见混淆
容易混淆的对象: comment
关键区别: docstring 是 字符串 literal (对象) 那个 documents 模块/函数/类. comment (# ...) 是 ignored 通过 解释器 完全. Docstrings 是 accessible at 运行时; comments 是 不.
相关术语
相关资源
相关课程
- Python 最佳实践
Docstrings.
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。