什么是数据类,它们与普通类别有何不同?
pep 557 将数据类引入Python Standard库中。它说,通过应用
下面显示的装饰器,它将生成“除其他事项外,@dataclass
__ INIT __()
”。
从数据级导入数据级 @DataClass 类库存ITEM: “”“用于跟踪库存中的项目的课程。”“” 名称:str unit_price:float Quantity_on_hand:int = 0 def tod total_cost(self) - >漂浮: 返回self.unit_price * self.quantity_on_hand
它还说,数据级是“默认情况下的可变名称”,但我不明白这意味着什么,也不了解数据类别与通用类别不同。
什么是数据类,什么时候最好使用它们?
PEP 557 introduces data classes into the Python standard library. It says that by applying the @dataclass
decorator shown below, it will generate "among other things, an __init__()
".
from dataclasses import dataclass @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
It also says dataclasses are "mutable namedtuples with default", but I don't understand what this means, nor how data classes are different from common classes.
What are data classes and when is it best to use them?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
数据类只是针对存储状态的常规类,而不是包含很多逻辑。每次创建主要由属性组成的类时,您都会进行数据类。
dataclasses
模块的作用是使其更容易创建数据类。它可以为您提供很多样板。当您的数据类必须具有可用时,这特别有用;因为这需要一个
__哈希__
方法以及__ eq __
方法。如果添加一个自定义__ epr __
易于调试的方法,它可能会变得非常详细:使用
dataclasses
您可以将其简化为:(基于 pep示例)。
同一类装饰器还可以生成比较方法(
__ lt __
,__ gt __
等)并处理不变性。名为Tuple
类也是数据类,但默认情况下是不变的(以及序列)。dataclasses
在这方面更加灵活,并且可以轻松地进行构造,以便它们可以填充与nequ nationtuple
class 相同的角色。PEP的灵感来自
attrs
attry project 更多(包括插槽,验证器,转换器,元数据等)。如果您想查看一些示例,我最近使用
dataclasses
用于我的几个代码出现解决方案,请参阅第7天, href =“ https://github.com/mjpieters/adventofcode/blob/master/2017/day%2008.ipynb” rel =“ noreferrer”>第8天>第8 ,第11天 and 第20天。如果您想在Python版本中使用
dataclasses
模块< 3.7,然后您可以安装 backported module (需要3.6)或使用attrs 上述项目。
Data classes are just regular classes that are geared towards storing state, rather than containing a lot of logic. Every time you create a class that mostly consists of attributes, you make a data class.
What the
dataclasses
module does is to make it easier to create data classes. It takes care of a lot of boilerplate for you.This is especially useful when your data class must be hashable; because this requires a
__hash__
method as well as an__eq__
method. If you add a custom__repr__
method for ease of debugging, that can become quite verbose:With
dataclasses
you can reduce it to:(Example based on the PEP example).
The same class decorator can also generate comparison methods (
__lt__
,__gt__
, etc.) and handle immutability.namedtuple
classes are also data classes, but are immutable by default (as well as being sequences).dataclasses
are much more flexible in this regard, and can easily be structured such that they can fill the same role as anamedtuple
class.The PEP was inspired by the
attrs
project, which can do even more (including slots, validators, converters, metadata, etc.).If you want to see some examples, I recently used
dataclasses
for several of my Advent of Code solutions, see the solutions for day 7, day 8, day 11 and day 20.If you want to use
dataclasses
module in Python versions < 3.7, then you could install the backported module (requires 3.6) or use theattrs
project mentioned above.概述
该问题已经解决。但是,此答案添加了一些实践示例,以帮助对数据阶层的基本理解。
nequtuple
等等。这是后一个短语的含义:
nequ tuple
或常规类。与普通类相比,您主要保存打字机代码。
功能
这是Dataclass功能的概述(TL; DR?请参见下一节中的摘要表)。
您在这里获得的
是您默认从数据级别获得的功能。
属性 +表示 +比较
这些默认值是通过自动将以下关键字设置为
true
:则可以打开
如果将适当的关键字设置为
true 。
顺序
现在实现了订购方法(超载运算符:
&lt;&lt;&lt; =&gt; =
),与functools.total_ordering
具有更强的平等测试。可见的,可变,
尽管该对象可能是可变的(可能是不希望的),但实现了哈希。
hashable,不可变的
hash现在正在实现,并更改对象或分配给属性。
总体而言,如果
unsafe_hash = true
或frozen = true
,则该对象是可用的。另请参见原始
优化
现在减少对象大小:
slots = true
在Python 3.10中添加。 (感谢@ajskateboarder)。在某些情况下,
插槽= true
/__插槽__
还提高了创建实例和访问属性的速度。另外,插槽不允许默认分配;否则,将提出valueerror
。如果__插槽__
已经存在,则slots = true
将导致typeerror
。请参阅此
请参阅参数>“ noreferrer”>参数match_args ,
kw_only
,插槽
,feekref_slot
。您无法
获得以下功能,必须手动实现特殊方法:
dunkaging
摘要表
*
__ ne ne __ ne __
不因此,” +这些方法不是自动生成的,需要在数据级别中进行手动实现。
附加功能
post initialization
继承
转换
将数据级转换为元组或dict, recursively :
限制
参考R.Hettinger
Overview
The question has been addressed. However, this answer adds some practical examples to aid in the basic understanding of dataclasses.
namedtuple
and others.Here is what the latter phrase means:
namedtuple
or a regular class.Compared to common classes, you primarily save on typing boilerplate code.
Features
This is an overview of dataclass features (TL;DR? See the Summary Table in the next section).
What you get
Here are features you get by default from dataclasses.
Attributes + Representation + Comparison
These defaults are provided by automatically setting the following keywords to
True
:What you can turn on
Additional features are available if the appropriate keywords are set to
True
.Order
The ordering methods are now implemented (overloading operators:
< > <= >=
), similarly tofunctools.total_ordering
with stronger equality tests.Hashable, Mutable
Although the object is potentially mutable (possibly undesired), a hash is implemented.
Hashable, Immutable
A hash is now implemented and changing the object or assigning to attributes is disallowed.
Overall, the object is hashable if either
unsafe_hash=True
orfrozen=True
.See also the original hashing logic table with more details.
Optimization
The object size is now reduced:
slots=True
was added in Python 3.10. (Thanks @ajskateboarder).In some circumstances,
slots=True
/__slots__
also improves the speed of creating instances and accessing attributes. Also, slots do not allow default assignments; otherwise, aValueError
is raised. If__slot__
already exists,slots=True
will cause aTypeError
.See more on slots in this blog post.
See more on arguments added in Python 3.10+:
match_args
,kw_only
,slots
,weakref_slot
.What you don't get
To get the following features, special methods must be manually implemented:
Unpacking
Summary Table
*
__ne__
is not needed and thus not implemented.+These methods are not automatically generated and require manual implementation in a dataclass.
Additional features
Post-initialization
Inheritance
Conversions
Convert a dataclass to a tuple or a dict, recursively:
Limitations
References
来自 pep Specification :
@DataClass
Generator将方法添加到类,否则您必须定义自己,例如__ epr __
,__ INT __ INT __ INT __
,__ lt __ lt __ 和
__ GT __
。From the PEP specification:
The
@dataclass
generator adds methods to the class that you'd otherwise have to define yourself like__repr__
,__init__
,__lt__
, and__gt__
.考虑此简单类
foo
这是
dir()
内置比较。左侧是foo
没有@Dataclass Decorator,右侧是@DataClass Decorator。这是另一个差异,在使用
Inspect
模块进行比较之后。Consider this simple class
Foo
Here is the
dir()
built-in comparison. On the left-hand side is theFoo
without the @dataclass decorator, and on the right is with the @dataclass decorator.Here is another diff, after using the
inspect
module for comparison.