Python · Module 07: Object-Oriented Programming (OOP)Tutorial 21 of 30
All Tutorials·~1.5 hrs

7.3 Dunder (Magic) Methods & Modern @dataclass

Make your custom classes behave like built-in Python types! Master __str__, __repr__, __eq__, __len__, operator overloading, and eliminate boilerplate with @dataclass.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

1. What Are Dunder (Double-Underscore) Methods?

Ever wonder how len(my_list), print(obj), or a + b work? Under the hood, Python translates built-in syntax into special dunder ("double-underscore") methods on your class:

Syntax You WriteMethod Python CallsPurpose
print(obj) / str(obj)obj.__str__()Human-friendly display for end users
repr(obj) (debugging/REPL)obj.__repr__()Unambiguous developer representation
a == ba.__eq__(b)Custom value equality (instead of RAM address!)
len(obj)obj.__len__()Enables len() and Truthy/Falsy checks
a + ba.__add__(b)Operator overloading (e.g., adding 2D Vectors)
PYTHON
class Vector:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __repr__(self):
        return f"Vector({self.x}, {self.y})"

    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)

v = Vector(2, 3) + Vector(4, 1)
print(v)   # Vector(6, 4)

2. Modern Python's Best Friend: @dataclass

Writing __init__, __repr__, and __eq__ by hand for every data model is tedious and bug-prone. Python 3.7+ introduced @dataclass — it writes all three for you automatically!

Visual: Why Modern Python Loves `@dataclass` (Zero Repetitive Boilerplate!)
Manual Class (~15 Lines)def __init__(self, title, price): ...def __repr__(self): ...def __eq__(self, other): ...Easy to forget __eq__ or __repr__!✓ @dataclass (4 Lines!)@dataclassclass Book:title: str ; price: floatAuto-generates __init__, __repr__, __eq__!
PYTHON
from dataclasses import dataclass, field

@dataclass
class Book:
    title: str
    price: float
    tags: list[str] = field(default_factory=list)  # Safe mutable default!

b1 = Book("Clean Python", 29.99)
b2 = Book("Clean Python", 29.99)

print(b1)         # Book(title='Clean Python', price=29.99, tags=[])
print(b1 == b2)   # True! (Automatic value equality!)

(Need an immutable record like a tuple with named fields? Use @dataclass(frozen=True)!)


3. Interactive Trace: @dataclass Equality & Representation

Tracing @dataclass Auto-Generated Methods
Interactive Line-by-Line Execution Trace · Step 1 of 5
1→b1 = Book("Python A-Z", 0.0)
2b2 = Book("Python A-Z", 0.0)
3same_val = (b1 == b2)
4same_obj = (b1 is b2)
5print(same_val, same_obj)
Variables in Memory
b1Book('Python A-Z', 0.0)Book
Console Output
(nothing printed yet)
What just happened: Auto-generated __init__ populates title and price on b1.

Quick Quiz: Module 7.3 — Dunder Methods & Dataclasses

Q1.Which 3 methods does `@dataclass` automatically generate by default?
Q2.How do you safely set an empty list default inside a `@dataclass`?
Q3.What is the main difference between `__str__` and `__repr__`?

Keep Exploring: Related Lessons & Tools

All Courses →