Sphinx中一组方法的文档字符串

5

在Sphinx生成的文档中,是否可以为方法组添加docstrings?

例如,我想要这样的文档:

class MyClass():
    """Doc of the class"""
    def __init__(self):
        pass

    """----- The following part is about imports -----"""

    def import_from_source_1(self):
        """Doc of import_from_source_1"""
        pass

    def import_from_source_2(self):
        """Doc of import_from_source_2"""
        pass

    """----- The following part is about exports-----"""

    def export_to_dest_1(self):
        """Doc of export_to_dest_1"""
        pass

    def export_to_dest_2(self):
        """Doc of export_to_dest_2"""
        pass

预期输出结果为:

MyClass
    Doc of the class

----- The following part is about imports -----
import_from_source_1
    Doc of import_from_source_1

import_from_source_2
    Doc of import_from_source_2

----- The following part is about exports-----
export_to_dest_1
    Doc of export_to_dest_1

export_to_dest_2
    Doc of export_to_dest_2

请注意,我的目标不仅仅是对方法进行分组(如在Sphinx中分组方法文档字符串所述),而是为分组添加文档字符串。

有人可以解释一下为什么会被踩吗?这样我就可以改进我的问题了。 - Simpom
1
一个 docstring 是在模块、函数、类或方法定义中作为第一条语句出现的字符串字面量。请参见 https://www.python.org/dev/peps/pep-0257/#id15。你不能像你的例子那样有“额外”的 docstrings。 - mzjn
我明白了。所以没有任何方法可以分组吗? - Simpom
1个回答

8
一个文档字符串是一个字符串字面量,出现在模块、函数、类或方法定义的第一条语句中 (https://www.python.org/dev/peps/pep-0257/#what-is-a-docstring)。你不能像问题中那样有“额外”的文档字符串。
然而,你可以使用automethod进行分组:
.. currentmodule:: mymodule

.. autoclass:: MyClass
   
   The following part is about imports
 
   .. automethod:: import_from_source_1
   .. automethod:: import_from_source_2
 
   The following part is about exports
 
   .. automethod:: export_to_dest_1
   .. automethod:: export_to_dest_2

1
这个解决方案对我来说是一个不错的折中方案:因为我需要自己组织方法,所以它们的文档不能完全自动化(这似乎很明显...)。 - Simpom

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接