你应该使用 Python @dataclass TL;DR 为什么你不应该使用 dataclass 什么是 dataclass?不卖?

2025-06-04

您应该使用 Python @dataclass

TL;DR

为什么不应该使用数据类

什么是数据类

还没卖出?

TL;DR

如果您使用的是 Python 3.7+,数据类将为您节省大量时间,使您的代码更简洁,甚至使您的代码更正确。

为什么不应该使用数据类

  1. 🕸 你目前使用的 Python 版本低于 3.7。很抱歉,3.7 版本新增了一些非常棒的功能,所以请尽快升级。
  2. 🚫 没有 2。如果您使用的是 Python 3.7+,数据类几乎肯定会在某些时候对您有所帮助。

什么是数据类

很高兴你问了🤓!Python 3.7 添加了一个名为 的小装饰器@dataclass。与其用英语解释它为什么这么棒,不如直接演示给你看。

你写的内容

from dataclasses import dataclass, field
from typing import List


@dataclass
class Pizza:
    # Each of these is called a field
    crust: str
    has_cheese: bool = True
    toppings: List[str] = field(default_factory=list)

Enter fullscreen mode Exit fullscreen mode

您现在可以做什么

from dataclasses import asdict, astuple, replace

# An __init__ is created which takes all fields as args or kwargs!
thick_cheesy = Pizza(crust='thick')

# __repr__ is generated, exclude any fields you don’t want
print(thick_cheesy)
# Prints "Pizza(crust='thick', has_cheese=True, toppings=[])"

# Handy method to create a dict, only includes fields
d = asdict(thick_cheesy)
assert d == {
    'crust': 'thick',
    'has_cheese': True,
    'toppings': [],
}

# Create a new object based on another object
with_olives = replace(thick_cheesy, toppings=['olives'])

# Make a tuple from the fields
t = astuple(with_olives)
assert t == ('thick', True, ['olives'])

# __eq__ is generated
assert with_olives != thick_cheesy # Effectively compares as tuples 

Enter fullscreen mode Exit fullscreen mode

等等,还有更多!💸

通过向装饰器传递一些选项@dataclass,您还可以:

  1. 使新形成的对象不可变(又称为冻结🥶)
  2. 加载未显示为字段的附加属性(也不在 asdict 中!)
  3. 快速添加比较器(<、> 等)

还没卖出?

如果数据类没有立刻让你兴奋,那又有什么关系呢?我很乐意阅读你的评论。

文章来源:https://dev.to/dbanty/you-should-use-python-dataclass-lkc
PREV
创业:选择科技的五步框架 思想实验
NEXT
Flask REST API:简介概要