如何在sphinx文档中显示实例属性?

问题描述 投票:0回答:2

有没有办法在sphinx文档中自动显示变量var1var2及其初始化值?

class MyClass:
    """    
    Description for class
    """

    def __init__(self, par1, par2):
       self.var1 = par1 * 2
       self.var2 = par2 * 2

    def method(self):
       pass
python python-sphinx
2个回答
73
投票

你的变量是实例变量,而不是类变量。

如果不将文档字符串(或

#:
“文档注释”)附加到变量,则不会记录它们。您可以执行以下操作:

class MyClass(object):
    """    
    Description for class 

    """

    def __init__(self, par1, par2):
        self.var1 = par1 #: initial value: par1
        self.var2 = par2 #: initial value: par2

    def method(self):
        pass

但我更愿意使用 info fields:

来包含变量文档
class MyClass(object):
    """    
    Description for class

    :ivar var1: initial value: par1
    :ivar var2: initial value: par2
    """

    def __init__(self, par1, par2):
        self.var1 = par1 
        self.var2 = par2 

    def method(self):
        pass

另请参阅:


0
投票

#:
文档注释:您还可以将文档注释放在变量上方

除了

self.var1 = par1 # Doc for var1
语法之外,您还可以:

主.py

class MyOtherClass:
    """
    This class does that.
    """
    pass

class MyClass:
    """
    Description for class.
    """

    #: Syntax also works for class variables.
    class_var: int = 1

    def __init__(self, par1: int, par2: MyOtherClass):
        #: Doc for var1
        self.var1: int = par1

        #: Doc for var2.
        #: Another line!
        self.var2: MyOtherClass = par2

    def method(self):
        """
        My favorite method.
        """
        pass

    @classmethod
    def cmethod():
        """
        My favorite class method.
        """
        pass

build.sh

sphinx-build . out

conf.py

import os
import sys
sys.path.insert(0, os.path.abspath('.'))
extensions = [ 'sphinx.ext.autodoc' ]
autodoc_default_options = {
    'members': True,
}
autodoc_typehints = "description"

索引.rst

.. automodule:: main

需求.txt

Sphinx==6.1.3

./build.sh
之后,
out/index.html
下的输出看起来像:

#:
语法记录在:https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html#directive-autoproperty

使用

:ivar:
:cvar:
代替

目前两种方法之间都存在权衡,遗憾的是没有一种明显更优越的方法。

缺点:

  • 您必须再次输入属性名称
  • 类型消失了,TODO 链接到功能请求

优点:

  • “变量:”分组看起来更干净,TODO 链接到功能请求

两者都可以更好:

  • 清楚地表明
    class_var
    是一个类变量? TODO 链接到功能请求
class MyClass:
    """
    Description for class.

    :ivar var1: Doc for var1
    :ivar var2: Doc for var2.
      Another line!
    :cvar class_var: Syntax also works for class variables.
    """

    class_var: int

    def __init__(self, par1: int, par2: MyOtherClass):
        self.var1: int = par1

        self.var2: MyOtherClass = par2

    def method(self):
        """
        My favorite method.
        """
        pass

    @classmethod
    def cmethod():
        """
        My favorite class method.
        """
        pass

产生:

相关:python的sphinx中var、cvar、ivar有什么区别?

在 Python 3.10、Ubuntu 22.10 上测试。

© www.soinside.com 2019 - 2024. All rights reserved.