简体   繁体   English

未显示文档字符串中的继承属性

[英]Inherited attributes in docstring not displayed

I'm trying to use Sphinx to document one base class and 2 child classes with google style docstring classes.我正在尝试使用 Sphinx 来记录具有 google 样式文档字符串类的一个基类和 2 个子类。 I'm particularly stuggling with inherited attributes:我特别纠结于继承的属性:

class Base(object):
    """Base class.

    Attributes:
         a (int): one attribute
         b (int): another one
    """

    def __init__(self):
        self.a = 3
        self.b = 5

class FirstChild(Base):
    """First Child of Base.

    Attributes:
        c (float): child class attribute
    """

    def __init__(self):
        self.c = 3.1

class SecondChild(Base):
    """Second Child of Base."""
    pass

Here is the rst file:这是第一个文件:

.. automodule:: my_package.my_module
    :members:
    :undoc-members:
    :show-inheritance:
    :inherited-members:

Sphinx displays attributes a and b only on class Base. Sphinx 仅在 Base 类上显示属性 a 和 b。 In FirstChild, there is only c, and no attribute in SecondChild, even with the :inherited-members: tag.在 FirstChild 中,只有 c,而在 SecondChild 中没有属性,即使有:inherited-members:标签。

Is there a way to have a, b and c displayed in the child classes without having to copy/paste descriptions in FirstChild/SecondChild docstrings ?有没有办法在子类中显示 a、b 和 c,而不必在 FirstChild/SecondChild 文档字符串中复制/粘贴描述?

Thanks!谢谢!

By using a decorator you can extract the attributes from the parent and insert them on the inherited class.通过使用装饰器,您可以从父类中提取属性并将它们插入到继承的类中。

    def docstring_inherit(parent):
        def inherit(obj):
            spaces = "    "
            if not str(obj.__doc__).__contains__("Attributes:"):
                obj.__doc__ += "\n" + spaces + "Attributes:\n"
            obj.__doc__ = str(obj.__doc__).rstrip() + "\n"
            for attribute in parent.__doc__.split("Attributes:\n")[-1].lstrip().split("\n"):
                obj.__doc__ += spaces * 2 + str(attribute).lstrip().rstrip() + "\n"
            return obj
    
        return inherit

    class Base(object):
        """Base class.
    
        Attributes:
             a (int): one attribute
             b (int): another one
        """
    
        def __init__(self):
            self.a = 3
            self.b = 5


    @docstring_inherit(Base)
    class FirstChild(Base):
    """First Child of Base.

    Attributes:
        c (float): child class attribute
    """
       def __init__(self):
           self.c = 3.1

I hope it resolves the question others with the same doubt.我希望它能解决其他有同样疑问的人的问题。

print(FirstChild.__doc__)
"""
First Child of Base.

    Attributes:
        c (float): child class attribute
        a (int): one attribute
        b (int): another one
        

"""

    

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

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