Python Mastery – From Basics to Brilliance / Object-Oriented Programming (OOP)

Dataclasses

πŸ“‹ Dataclasses

A dataclass is a special type of class used mainly for storing data.

It automatically generates common methods like __init__(), __repr__(), and __eq__() for us.


πŸ”Ή Without Dataclass

Normally, we would write:

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

student = Student("Codeveda", 23)

print(student.name)

✨ Using @dataclass

from dataclasses import dataclass

@dataclass
class Student:
    name: str
    age: int

student = Student("Alice", 23)

print(student) #Student(name='Alice', age=23)

Python automatically creates the __init__() and __repr__() methods.


🏷️ Default Values

You can provide default values:

from dataclasses import dataclass

@dataclass
class Student:
    name: str
    age: int = 18

student = Student("Alice")

print(student) #Student(name='Alice', age=18)

⭐ Why Use Dataclasses?

They are useful when a class mainly holds data.


🧠 Remember

Dataclass = A convenient way to create classes that mainly store data.

@dataclass
class Student:
    name: str
    age: int

Python handles much of the repetitive class code for you.