Python Dataclass

Python Dataclass

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.

Examples

1. Creating a simple dataclass

In this example, we’ll create a dataclass to represent a Point with x and y coordinates.

Python Program

from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

# Create an instance of Point
p = Point(3, 5)
print(p)
Run Code Copy

The @dataclass decorator automatically generates the __init__, __repr__, and __eq__ methods based on the annotated attributes.

Output

Point(x=3, y=5)

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.

Python Program

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)
Run Code Copy

Output

Student(name='Ram', age=21, student_id='12345')

Summary

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.

Related Tutorials

Code copied to clipboard successfully 👍