【问题标题】:Using Python docstring override and extend verbs in Sphinx在 Sphinx 中使用 Python 文档字符串覆盖和扩展动词
【发布时间】:2020-10-01 15:18:37
【问题描述】:

我正在使用 Sphinx 从我的文档字符串生成文档,这些文档字符串的格式为 Sphinx style。根据PEP-257,我应该使用动词“覆盖”和“扩展”来表示继承的方法是否被替换或调用。

如果一个类是另一个类的子类并且它的行为主要是从那个类继承的,它的文档字符串应该提到这一点并总结差异。用动词“override”表示子类方法替换超类方法,不调用超类方法;使用动词“extend”表示子类方法调用超类方法(除了它自己的行为)。

由于我是新手,我不清楚我应该如何以 Sphinx 格式执行此操作。我是简单地使用我的描述中的一个词,还是有一个像:return: 这样的 我应该应用?该指令是在 子类 级别上给出的,是动词的位置还是我也将它们添加到各个方法中?

class A:
    """This is my base class."""

    def method_a(self):
        """My base method a."""
        pass

    def method_b(self):
        """My base method b."""
        pass


class B(A):
    """This is the subclass that inherits from :class: A."""

    def method_a(self):
        """This method replaces the inherited method_a."""
        print("overridden")

    def method_b(self):
        """This method calls the inherited method_b."""
        super(B, self).method_b()
        print("extended")

class B 及其方法的一组简单但正确的文档字符串是什么样的?

【问题讨论】:

    标签: python python-3.x python-sphinx docstring


    【解决方案1】:

    直接来自 Python 文档的一个示例是 defaultdict 集合。它只覆盖了一种字典方法(__missing__(key) 方法)。

    defaultdict 是内置 dict 类的子类。它覆盖了一个方法(...)其余功能与 dict 类相同,此处未记录。(...)所有剩余参数都被视为与传递给 dict 构造函数一样,包括关键字论据。

    文档在散文中明确说明了这一点,记录了被覆盖的方法,并解释了超类和子类构造函数签名之间的参数差异。

    我是简单地使用我的描述中的一个词,还是我需要申请的键,例如 :return:?

    你所说的“key”实际上被称为docstring section。没有特定的 "docstring section" 来表示“覆盖”或“扩展”,因为这是隐含的。如果子类定义的方法与其超类的方法名称完全相同,则该方法必然是覆盖或扩展的。

    总之,您会惊讶地发现您的文档实际上是正确的。最多您可以口头添加“覆盖”和“扩展”以及对超类方法的交叉引用,如下所示:

    class B(A):
        """Neither method_a nor method_b are inherited.
           Both methods are redefined in this class.
        """
        def method_a(self):
            """This method overrides :meth:`A.method_a`."""
            print("overridden")
    
        def method_b(self):
            """This method extends :meth:`A.method_b`."""
            super().method_b()
            print("extended")
    

    您的示例在签名中缺少参数,以下答案显示how overloaded and extended methods having differing parameters can be documented

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-09
      相关资源
      最近更新 更多