简体   繁体   English

Sphinx autodoc:继承文档字符串而不继承 class

[英]Sphinx autodoc: inherit docstrings without inheriting class

I have two classes which share an API through duck typing, but do not share any inheritance:我有两个类通过鸭子类型共享一个 API,但不共享任何 inheritance:

class A:
    def method():
        """Does something."""
        pass

class B:
    def method():
        pass

I have written docstrings for A , but not B .我已经为A编写了文档字符串,但没有为B编写文档字符串。 Since the two classes share the same API semantics, their docstrings are mostly the same.由于这两个类共享相同的 API 语义,因此它们的文档字符串大多相同。 I do not wish to repeat the same docstrings in two different places.我不想在两个不同的地方重复相同的文档字符串。

If B inherited from A , then autodoc has tools to inherit parent class docstrings, but I don't want B to inherit from A .如果B继承自A ,则 autodoc 具有继承父 class 文档字符串的工具,但我不希望BA继承。

I could make both classes inherit from an abc.ABC abstract class and put the docstrings there, but that would be a lot of added code for no purpose other than documentation.我可以让这两个类都继承自abc.ABC抽象 class 并将文档字符串放在那里,但除了文档之外,这将是大量添加的代码。

Is there any way to tell autodoc to copy the docstrings from another class?有没有办法告诉 autodoc 从另一个 class 复制文档字符串?

I'm not sure you can tell autodoc to do that, but you can copy it in the code:我不确定您是否可以告诉 autodoc 这样做,但您可以将其复制到代码中:

class A:
    def method():
        """Does something."""
        pass

class B:
    def method():
        pass
    method.__doc__ = A.method.__doc__

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM