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

I have some existing Python 3.6 code that I'd like to move to Python 3.7 dataclasses. I have __init__ methods with nice docstring documentation, specifying the attributes the constructors take and their types.

However, if I change these classes to use the new Python dataclasses in 3.7, the constructor is implicit. How do I provide constructor documentation in this case? I like the idea of dataclasses, but not if I have to forego clear documentation to use them.

edited to clarify I'm using docstrings presently

解决方案

The napoleon-style docstrings as they are described in the sphinx docs (see the ExampleError class for their take on it) explicitly touch on your case:

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

And if you do not want this behavior, you have to explicitly tell sphinx that the constructor docstring and the class docstring are not the same thing.

Meaning, you can just paste your constructor info into the body of the class docstring.

In case you build documents from your docstrings, these are the granularities that can be achieved:

1) The bare minimum:

@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) Additional constructor parameter description:

@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) Additional attribute description:

@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

Parameter and attribute descriptions can of course be combined as well, but since dataclasses should be straight forward mappings I don't see a reason to do so.

In my opinion, 1) would do for small or simple dataclasses -- it already includes the constructor signature with their respective types, which is plenty for a dataclass. If you want to say more about each attribute, 3) would serve best.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值