什么是Sphinx注释?

一、什么是Sphinx注释? Sphinx注释是Python文档字符串(docstring)的一种标准格式,主要用于:

  1. 生成专业级API文档(通过Sphinx工具)
  2. 提供IDE智能提示支持
  3. 作为代码内联文档

与普通注释(#)不同,Sphinx注释使用三重引号"""包裹,具有特定语法规则。

二、基本语法规则

  1. 模块级注释
python 复制代码
"""Module-level docstring.

This is a brief description of the module.
More detailed explanation goes here.
"""
  1. 类注释
python 复制代码
class MyClass:
    """Class-level docstring.

    Args:
        param1 (type): Description of param1
        param2 (type): Description of param2

    Attributes:
        attr1 (type): Description of attr1
    """
  1. 函数/方法注释
python 复制代码
def my_function(param1, param2):
    """Function-level docstring.

    Args:
        param1 (type): Description
        param2 (type): Description

    Returns:
        type: Description of return value

    Raises:
        ErrorType: When something bad happens
    """

三、核心字段说明

字段 用途 示例
Args 参数说明 param1 (int): The first parameter
Returns 返回值说明 bool: True if successful
Raises 可能抛出的异常 ValueError: If input is invalid
Attributes 类属性说明 name (str): The name of instance
Examples 使用示例 >>> obj = MyClass()
Note 重要说明 Note: This is critical for...
.. versionadded:: 版本标记 .. versionadded:: 1.2.0

四、两种主流风格

  1. Google风格(推荐)
python 复制代码
def add(a, b):
    """Add two numbers.

    Args:
        a (int or float): First number
        b (int or float): Second number

    Returns:
        int or float: Sum of a and b

    Example:
        >>> add(2, 3)
        5
    """
    return a + b
  1. NumPy风格
python 复制代码
def subtract(a, b):
    """Subtract two numbers.

    Parameters
    ----------
    a : int or float
        First number
    b : int or float
        Second number

    Returns
    -------
    int or float
        Result of a - b
    """
    return a - b

五、实际应用示例

python 复制代码
class MolecularDataset:
    """AM1 molecular dataset handler.

    Args:
        data_path (str): Path to .pkl file
        max_atoms (int, optional): Max atoms per molecule. Defaults to 64.
        shuffle (bool, optional): Whether to shuffle data. Defaults to True.

    Attributes:
        elements (ndarray): Atomic numbers array
        coordinates (ndarray): 3D coordinates array

    Example:
        >>> dataset = MolecularDataset('data.pkl')
        >>> len(dataset)
        100
    """

    def __init__(self, data_path, max_atoms=64, shuffle=True):
        """Initialize with data path and parameters."""
        self.data_path = data_path
        self.max_atoms = max_atoms
        self.shuffle = shuffle

    def load(self):
        """Load molecular data from file.

        Returns:
            bool: True if loaded successfully

        Raises:
            FileNotFoundError: If data file doesn't exist
        """
        if not os.path.exists(self.data_path):
            raise FileNotFoundError
        return True

六、生成文档的步骤

  1. 安装Sphinx:
bash 复制代码
pip install sphinx sphinx-rtd-theme
  1. 创建文档项目:
bash 复制代码
sphinx-quickstart docs
  1. 配置docs/source/conf.py:
python 复制代码
extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.napoleon'  # 支持Google/NumPy风格
]
  1. 编写.rst文件(如api.rst):
rst 复制代码
API Reference
=============

.. automodule:: your_module
   :members:
   :show-inheritance:
  1. 生成HTML文档:
bash 复制代码
cd docs
make html

生成的文档将位于docs/_build/html目录,支持: • 自动参数类型链接

• 交互式示例代码

• 版本变更追踪

• 跨模块引用

七、IDE支持情况

IDE 功能支持
PyCharm 自动补全、悬浮提示、文档快速导航
VS Code 通过Python插件支持基本文档显示
Jupyter 使用?和??查看文档
Spyder 对象检查器(Object Inspector)显示完整文档
相关推荐
信誓旦旦的程序猿2 小时前
【Python量化实战宝典 #08】可转债与债券接口手册:转股价·溢价率·纯债价值(Python 可跑)
java·python·股票数据api·股票数据api接口·股票api数据接口·股票量化数据api·股票量化数据接口
砚底藏山河2 小时前
python量化:行情数据回溯
java·开发语言·python·金融·maven
今年下半年2 小时前
AI智能体项目实战记录(02):初始化 Python 项目
开发语言·人工智能·python·fastapi
Williamtym2 小时前
PickGo Lab实践:用浏览器、Python和MCP串起机器人搬运仿真
开发语言·python·机器人
CS创新实验室3 小时前
Python 对象“死“了之后去了哪?——引用计数与分代垃圾回收
开发语言·jvm·python
CCblandy3 小时前
雪花 ID 四个边界实测:时钟回拨重号 500 个,前端 JSON.parse 直接丢精度
后端·python·算法·性能优化·架构
quantdash_cc3 小时前
Pandas 处理分钟级股票行情:从原始数据清洗到 K 线聚合
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
把我格子衫拿来3 小时前
VTK 9.5 与 Qt 6 联合开发:从嵌入三维窗口到可维护的桌面架构
c++·python·qt·vtk·三维可视化
cpolar技术支持3 小时前
把配置发出去怕带出密钥?先把含凭据配置转成脱敏只读快照,用 cpolar 给同事核对差异
运维·python·内网穿透·cpolar·配置脱敏
惊讶的猫4 小时前
langchian_agent的高级使用
python