我正在尝试使用Sphinx来记录一个基类和2个带有Google样式docstring类的子类。我特别擅长继承属性:
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
这是第一个文件:
.. automodule:: my_package.my_module
:members:
:undoc-members:
:show-inheritance:
:inherited-members:
Sphinx仅在类Base上显示属性a和b。在FirstChild中,即使使用:inherited-members:
标记,SecondChild中也只有c,没有属性。
有没有办法在子类中显示a,b和c而无需在FirstChild / SecondChild文档字符串中复制/粘贴描述?
谢谢!
答案 0 :(得分:0)
通过使用装饰器,您可以从父级提取属性,并将其插入到继承的类中。
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
我希望它能以同样的疑问解决其他人的问题。
print(FirstChild.__doc__)
"""
First Child of Base.
Attributes:
c (float): child class attribute
a (int): one attribute
b (int): another one
"""