You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python文档字符串中规范添加函数调用示例?

在Python文档字符串中添加函数调用示例的方法

Python里没有像R的@examples那样官方强制的标签,但你可以根据项目需求选择几种常用的方式,以下是具体实现:

1. 自定义标签风格(最接近R的@examples)

直接在文档字符串里用:example:或者@example作为标识,后面跟上示例代码,就像你期望的那样:

def my_func(x):
    """prints x.
    :param x: string to print
    :example: 
        my_func("hello world!")
    """
    print(x)

这种方式简单直观,大部分Python编辑器(比如PyCharm)都能识别并高亮显示示例,完全不需要依赖第三方工具。

2. Google风格文档字符串

很多项目喜欢用这种风格,明确用Examples:作为小节标题,示例可以带运行结果,还能通过doctest直接验证:

def my_func(x):
    """prints x.

    Args:
        x: string to print

    Examples:
        >>> my_func("hello world!")
        hello world!
    """
    print(x)

运行python -m doctest your_script.py就能自动检查示例是否正确,实用性很强。

3. reStructuredText风格(适配Sphinx)

如果后续需要生成正式文档,这种格式更规范,用.. code-block:: python包裹代码块:

def my_func(x):
    """prints x.
    :param x: string to print

    .. code-block:: python
        my_func("hello world!")
    """
    print(x)

Sphinx能直接解析这种格式生成美观的文档,但即使不用Sphinx,这种格式也保持了良好的可读性。

4. NumPy风格(适合科学计算项目)

结构更严谨,适合数据科学、机器学习类项目:

def my_func(x):
    """prints x.

    Parameters
    ----------
    x : str
        string to print

    Examples
    --------
    >>> my_func("hello world!")
    hello world!
    """
    print(x)

总结

Python没有统一的强制标准,选哪种风格取决于团队习惯和项目需求。如果要最接近R的@examples体验,自定义:example:标签的方式最直接,不需要额外学习成本。

内容的提问来源于stack exchange,提问作者tover

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 01:51:03