gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 18:27:10 24 4
gpt4 key购买 nike

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

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

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

最佳答案

the sphinx docs 中描述的拿破仑风格的文档字符串(请参阅 ExampleError 类了解他们对此的看法)明确涉及您的案例:

The _init_ method may be documented in either the class level docstring, or as a docstring on the _init_ method itself.

如果你不想要这种行为,你必须 explicitly tell sphinx构造函数文档字符串和类文档字符串不是一回事。

意思是,您只需将构造函数信息粘贴到类文档字符串的主体中即可。


如果您从文档字符串构建文档,这些是可以实现的粒度:

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) 最合适。

关于python - 如何使用 Python 数据类记录类的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51125415/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com