首页 > 解决方案 > 类定义中这些带引号的字符串是什么?

问题描述

我正在查看一些 Python 代码,这些代码以我以前从未见过的方式引用了类定义中使用的字符串:

class Foo:
    """
    Docstring for the class. This one I understand, of
    course. I'm wondering about the two strings below.
    """

    one: str
    "One thing."
    another: str
    "Another thing."

    def __init__(self):
    # etc, etc.

最后两个引用的字符串是做什么用的?我猜 Python 运行时会忽略它们,并且有一些外部工具使用它们?

标签: pythonpython-3.x

解决方案


这些可能是为 Sphinx autodoc 准备的。Python 会忽略它们——Python 本身不支持属性的文档字符串——但 Sphinx 自动文档将属性定义之后的字符串文字识别为该属性的文档。我认为注释可能会用于此目的,但我没有设置来测试它。


推荐阅读