如何使用Python数据类记录类的构造函数?


问题内容

我有一些现有的Python 3.6代码,我想移至Python
3.7数据类。我有__init__带有漂亮文档字符串文档的方法,指定了构造函数采用的属性及其类型。

但是,如果我更改这些类以使用3.7中的新Python数据类,则构造函数是隐式的。在这种情况下,如何提供构造函数文档?我喜欢数据类的想法,但是如果我必须放弃明确的文档才能使用它们,则不喜欢。

编辑以澄清我目前正在使用文档字符串


问题答案:

狮身人面像文档中描述的拿破仑式文档字符串(请参见ExampleError该类的说明)明确涉及您的情况:

__init__方法可以记录在类级别docstring中,也可以记录在__init__方法本身上。

而且,如果您不希望出现这种情况,则必须明确告诉sphinx构造函数docstring和类docstring不是同一件事。

意思是,您只需将构造函数信息粘贴到类docstring的主体中。


如果您使用文档字符串构建文档,则可以实现以下粒度:

1)最低要求:

@dataclass
class TestClass:
    """This is a test class for dataclasses.

    This is the body of the docstring description.
    """
    var_int: int
    var_str: str

在此处输入图片说明

2)额外的构造函数参数说明:

@dataclass
class TestClass:
    """This is a test class for dataclasses.

    This is the body of the docstring description.

    Args:
        var_int (int): An integer.
        var_str (str): A string.

    """
    var_int: int
    var_str: str

在此处输入图片说明

3)附加属性描述:

@dataclass
class TestClass:
    """This is a test class for dataclasses.

    This is the body of the docstring description.

    Attributes:
        var_int (int): An integer.
        var_str (str): A string.

    """
    var_int: int
    var_str: str

在此处输入图片说明


参数和属性的描述当然也可以合并,但是由于数据类应该是直接的映射,所以我看不出这样做的理由。

在我看来, 1) 将适用于小型或简单的数据类-它已经包含构造函数签名及其各自的类型,对于数据类而言已经足够了。如果您想对每个属性多说几句,则
3) 效果最佳。