Python data class
For Python 3.7+, is a simple class that mainly stores data, using the Python decorators @dataclass, it adds the __init__(), __repr__() and __eq__() methods, as an example for a Student data class:
from dataclasses import dataclass
@dataclass
class Student:
name: str
age: int
grades: list[float]
# Creating an instance
student = Student("Alice", 20, [85.5, 92.0, 88.5])
# The __repr__ is automatically generated
print(student) # Student(name='Alice', age=20, grades=[85.5, 92.0, 88.5])
and without data class
class StudentWithoutDataclass:
def __init__(self, name: str, age: int, grades: list[float]):
self.name = name
self.age = age
self.grades = grades
def __repr__(self):
return f"StudentWithoutDataclass(name='{self.name}', age={self.age}, grades={self.grades})"
def __eq__(self, other):
if not isinstance(other, StudentWithoutDataclass):
return NotImplemented
return (self.name == other.name and
self.age == other.age and
self.grades == other.grades)