【问题标题】:How to refer child class attributes in the parent class docstring?如何在父类文档字符串中引用子类属性?
【发布时间】:2020-05-16 11:06:47
【问题描述】:

我正在使用:inherited-members: 来显示父方法。

在为子类生成的文档中,是否可以引用子类?

class Parent:
   """This is a {Child class name} class

   This is in the {Child group attribute} group
   """
   group = ''
   ...

class Child(Parent):
   group = 'TheChild'
   ...

在为孩子生成的文档中,我想看看:

> class Child(Parent)
>   Bases: Parent
>   This is a Child class.
>   It is in the TheChild group

Sphinx 可以做到这一点吗?

【问题讨论】:

  • 在这种情况下,group(或TheChild 组)是什么?是一群孩子吗?是你定义的组吗?是 Child 类的文档字符串吗?
  • group 只是一个类属性。我可以很容易地称它为xyz。每个孩子都将使用自己的值覆盖 group 属性。这有帮助吗?
  • 即使你能做到,它也会造成一个令人困惑的文档字符串。
  • @user2357112supportsMonica 如果您知道如何阅读 Python Sphinx,这并不令人困惑。此外,对象名称是完全限定的。您可以选择在 docstring 或 rst 文件中记录,该选择由每个开发人员自行决定。除非您制作的 PEP 另有建议。

标签: python parent-child python-sphinx docstring cross-reference


【解决方案1】:

您可以在文档字符串中使用 Sphinx Cross-referencing syntax,以及来自 Python domain 的相应 roles。之后,您的.rst 中的autodoc directives 负责其余的工作。

示例 parent_child.py

class Parent:
    """
    This is a :py:class:`Child` class.

    This is in the :py:data:`Child.group` attribute.
    """
    group = 'TheParent'


class Child(Parent):
    group = 'TheChild'

parent_child.rst

Parent\_Child
=============

.. autoclass:: parent_child.Parent
    :members:
    :undoc-members:
    :show-inheritance:

.. autoclass:: parent_child.Child
    :members:
    :undoc-members:
    :show-inheritance:

结果:

【讨论】:

  • 他们希望 Child 内容出现在 Child 文档中,而不是父文档中。
  • @user2357112supportsMonica Python documentation has examples otherwise。向核心开发人员提出您的反对意见。
  • 这没有任何意义。标准库中的某些特定类以一种方式记录的事实不会改变问题要求生成其文档的方式。另外,您所做的甚至与您链接的 stdlib 文档不匹配。
  • @user2357112supportsMonica OP认为不然,官方文档给出了一个例子,(我不必向你解释任何事情,问题不清楚 - 你仍然不明白 -如果 OP 有不同的澄清,我会调整解决方案。)
猜你喜欢
  • 1970-01-01
  • 2012-12-05
  • 1970-01-01
  • 2020-05-09
  • 1970-01-01
  • 1970-01-01
  • 2019-09-04
  • 1970-01-01
  • 2022-11-14
相关资源
最近更新 更多