Python DocString(Google 风格):如何记录类属性?

Zan*_*dar 10 python docstring class-attributes python-sphinx

我有这个小例子:

"""Sandbox module"""

class Toto:
    """
    This class is an example

    Attributes:
        class_attribute (str): The class attribute #Unresolved reference
        instance_attribute (str): The instance attribute #OK
    """

    class_attribute = ""

    def __init__(self):
        self.instance_attribute = ""
        pass
Run Code Online (Sandbox Code Playgroud)

这会触发未解决的参考警告我应该如何正确记录类属性?

A. *_*dry 5

假设您想使用napoleon将文档字符串呈现为文档,sphinx开发人员正在努力寻找一种将自定义部分添加到类级文档字符串的方法(请参阅问题#33)。

目前,在Google Style Docstrings Example中,该class ExamplePEP526Class示例指出

如果类具有公共属性,它们可能会记录在此处的一个Attributes部分中,并遵循与函数Args部分相同的格式。如果napoleon_attr_annotations 为 True,则可以使用注释在类主体中指定类型PEP 526

PEP 526为类型提示添加了变量注释。因此,您的代码现在可以编写为:

"""Sandbox module"""

class Toto:
    """ This class is an example

    Attributes:
        class_attribute (str): (class attribute) The class attribute
        instance_attribute (str): The instance attribute
    """

    class_attribute: str = ""

    def __init__(self):
        self.instance_attribute: str = ""
Run Code Online (Sandbox Code Playgroud)

一方面,您似乎忘记在定义它str之后添加类型提示,因此(如果使用外部类型检查器)可能无法发现其类型。class_attributemypy

讽刺的是,相反的情况也会起作用:在napoleonversion中3.4,如果napoleon_attr_attributes设置为True,则

如果文档字符串中记录的属性没有类型并且在类主体中具有注释,则使用该类型。

其次,方法pass末尾的__init__是允许的,但没有必要,因为您instance_attribute在那里定义了。

我提到问题 #33 是因为,就我个人而言,我宁愿将标题“类变量”称为“属性”,其本身并不区分实例与类属性/变量。目前,您可能想像我一样在属性描述中添加自己的符号。

对我来说,我的类属性要么比实例属性少,要么根本没有,所以我只注意属性是否是类属性(否则,它是实例属性)。这样,我就不必(instance attribute)在所有实例属性旁边写入。或者,您可以尝试class在括号中放入与optional列出的类型相同的类型:

class_attribute (str, class): The class attribute
Run Code Online (Sandbox Code Playgroud)

我不确定这是否会起作用或破坏。如果它损坏了,将来添加到文档字符串语法中肯定会很好(我认为这看起来更干净)。

最后,您可以将类变量记录为PEP 257中定义的属性文档字符串以及此 SO 答案,方法是将文档字符串直接放在赋值下方,如下所示:

"""Sandbox module"""

class Toto:

    class_attribute: str = ""
    """class_attribute (str): (class attribute) The class attribute"""

    def __init__(self):
        """ This class is an example
    
        Attributes:
            instance_attribute (str): The instance attribute
        """
        self.instance_attribute: str = ""
Run Code Online (Sandbox Code Playgroud)


agi*_*ius -1

尝试这个:

"""
    Sandbox module
    ~~~~~~~~~~~~~~
"""

class Toto:
    """This class is an example

    Attributes:
        instance_attribute (str): The instance attribute #OK
    """
    
    #: str: The class attribute #Unresolved reference
    class_attribute = ""

    def __init__(self):
        self.instance_attribute = ""
        pass
Run Code Online (Sandbox Code Playgroud)

这对我使用 sphinx 来说效果很好。