Dataclass

什么是Dataclass

dataclass 是 Python 3.7+ 中引入的一个装饰器,它的主要目的是简化类的创建,特别是那些主要用于存储数据的类。在没有 dataclass 之前,如果你要创建一个简单的数据类,通常需要手动编写很多样板代码,比如:

class Student:

​ def _init_(self, name: str, age: int, student_id: str):

​ self.name = name

​ self.age = age

​ self.student_id = student_id

​ def _repr_(self):

​ return f"Student(name={self.name}, age={self.age}, student_id={self.student_id})"

​ def _eq_(self, other):

​ if other.class is self.class:

​ return (self.name, self.age, self.student_id) == (other.name, other.age, other.student_id)

​ return False

Dataclass的作用

@dataclass 是一个类装饰器,它修饰的是类定义。当你在类定义前加上 @dataclass 时,Python 会自动为这个类生成一些特殊方法,包括:

  • __init__(): 初始化方法
  • __repr__(): 对象的字符串表示
  • __eq__(): 对象比较方法
  • __hash__(): 哈希方法(如果所有字段都是可哈希的)
  • 以及其他一些有用的方法
    from dataclasses import dataclass
posted @ 2025-08-12 07:14  rhoshu  阅读(26)  评论(0)    收藏  举报