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.
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 Write | Method Python Calls | Purpose |
|---|---|---|
print(obj) / str(obj) | obj.__str__() | Human-friendly display for end users |
repr(obj) (debugging/REPL) | obj.__repr__() | Unambiguous developer representation |
a == b | a.__eq__(b) | Custom value equality (instead of RAM address!) |
len(obj) | obj.__len__() | Enables len() and Truthy/Falsy checks |
a + b | a.__add__(b) | Operator overloading (e.g., adding 2D Vectors) |
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!
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
Quick Quiz: Module 7.3 — Dunder Methods & Dataclasses
Keep Exploring: Related Lessons & Tools
All Courses →Test regular expressions live with color-coded match highlights, capture group inspection, plain-English token breakdown, find-and-replace, and Python/JS snippets.
Paste any Python, JS, Java, or C++ snippet to estimate Time & Space complexity, or enter input size N to see which algorithms pass in 1s.