In this tutorial, you will learn about the dataclass decorator in Python, which simplifies the creation of classes for storing and managing data.
dataclass is used to define classes that primarily store data unlike a regular class. It automatically generates special methods like __init__, __repr__, __eq__, and more. This reduces the boilerplate code typically needed for such classes.
1. Creating a simple dataclass
In this example, we’ll create a dataclass to represent a Point with x and y coordinates.
Run Code Copy
from dataclasses import dataclass @dataclass class Point: x: int y: int # Create an instance of Point p = Point(3, 5) print(p)
The @dataclass decorator automatically generates the __init__, __repr__, and __eq__ methods based on the annotated attributes.
2. Dataclass Inheritance
Dataclasses can also inherit from other classes and implement methods.
In this example, the Student class inherits from the Person class and extends it with an additional attribute.
Run Code Copy
from dataclasses import dataclass @dataclass class Person: name: str age: int @dataclass class Student(Person): student_id: str student = Student(name="Ram", age=21, student_id="12345") print(student)
Student(name='Ram', age=21, student_id='12345')
In this Python dataclasses tutorial, we learned about dataclass in Python, how to create a dataclass, how to create a dataclass that inherits another dataclass, etc., with the help of examples.