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

时间:2018-07-01 17:21:23

标签: python documentation python-3.7 python-dataclasses

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

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

已编辑,以阐明我当前正在使用文档字符串

3 个答案:

答案 0 :(得分:5)

the sphinx docs中描述的拿破仑式文档字符串(有关其用法,请参见ExampleError类)明确涉及您的情况:

  

__ init__方法可以记录在类级别docstring中,也可以记录为__init__方法本身的docstring。

如果您不希望出现这种情况,则必须explicitly tell sphinx构造函数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

enter image description here

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

enter image description here

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

enter image description here


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

在我看来, 1)将适用于小型或简单的数据类-它已经包括具有各自类型的构造函数签名,这对于一个数据类来说已经足够了。如果您想进一步说明每个属性,最好使用 3)

答案 1 :(得分:4)

数据类的主要优点是它们是自记录的。假设您的代码读者知道数据类是如何工作的(并且属性已适当命名),则带类型注释的类属性应该是构造函数的出色文档。请参见官方dataclass docs的示例:

@dataclass
class InventoryItem:
    '''Class for keeping track of an item in inventory.'''
    name: str
    unit_price: float
    quantity_on_hand: int = 0

    def total_cost(self) -> float:
        return self.unit_price * self.quantity_on_hand

如果您不希望代码的读者知道数据类的工作原理,那么您可能想重新考虑使用它们,或者在@dataclass装饰器之后的嵌入式注释中添加说明或指向文档的链接。如果您确实需要数据类的文档字符串,建议将构造函数文档字符串放在文档字符串类中。对于上面的示例:

'''Class for keeping track of an item in inventory.

Constructor arguments:
:param name: name of the item
:param unit_price: price in USD per unit of the item
:param quantity_on_hand: number of units currently available
'''

答案 2 :(得分:1)

我认为最简单的方法是:

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

    This is the body of the docstring description.

    """
    var_int: int  #: An integer.

    #: A string.
    #: (Able to have multiple lines.)
    var_str: str

    var_float: float
    """A float. (Able to have multiple lines.)"""

不知道为什么@Arne 渲染的结果看起来像那样。就我而言,无论文档字符串如何,数据类中的属性都将始终显示。即:

1) 最低要求:

2) 附加构造函数参数说明:

3) 附加属性说明:

可能是因为我在 conf.py 中设置了错误(Sphinx v3.4.3,Python 3.7):

extensions = [
    "sphinx.ext.napoleon",
    "sphinx.ext.autodoc",
    "sphinx_autodoc_typehints",
    "sphinx.ext.viewcode",
    "sphinx.ext.autosectionlabel",
]

# Napoleon settings
napoleon_google_docstring = True
napoleon_include_init_with_doc = True