在Sphinx中使用Python文档字符串重写和扩展谓词

2024-04-26 17:32:51 发布

您现在位置:Python中文网/ 问答频道 /正文

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

If a class subclasses another class and its behavior is mostly inherited from that class, its docstring should mention this and summarize the differences. Use the verb "override" to indicate that a subclass method replaces a superclass method and does not call the superclass method; use the verb "extend" to indicate that a subclass method calls the superclass method (in addition to its own behavior).

因为我是新手,所以我不清楚我应该如何在斯芬克斯格式中做到这一点。我是简单地使用我描述中的一个词,还是有一个我应该应用的比如: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及其方法,一组简单但正确的docstring是什么样子的


Tags: andtheto方法文档selfthatis
1条回答
网友
1楼 · 发布于 2024-04-26 17:32:51

Python文档中的一个直接示例是^{}集合。它只覆盖了字典的一种方法(即__missing__(key)方法)

defaultdict is a subclass of the built-in dict class. It overrides one method (...) The remaining functionality is the same as for the dict class and is not documented here.(...) All remaining arguments are treated the same as if they were passed to the dict constructor, including keyword arguments.

文档以散文的形式明确说明了这一点,文档记录了重写的方法,并解释了超类和子类构造函数签名之间的参数差异

Do I simply use one of the words in my description or is this a key like :return: that I need to apply?

你所谓的“键”实际上被称为docstring section。没有特定的“docstring节”来指示“覆盖”或“扩展”,因为这是隐式的。如果子类定义的方法与其超类的方法具有完全相同的名称,则该方法必须重写或扩展

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

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

相关问题 更多 >