Magic Methods and Dataclasses
Overload operators, create callable objects, and use modern dataclasses for clean data models.
Learning objectives
- Implement magic methods like __repr__, __eq__, and __len__
- Use @dataclass decorator to generate boilerplate constructors automatically
Lesson material
Python Dataclasses
Introduced in Python 3.7, @dataclass auto-generates __init__, __repr__, and __eq__ methods based on type annotations.
Example code
from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float
p1 = Point(1.0, 2.0)
p2 = Point(1.0, 2.0)
print(p1)
print("p1 == p2:", p1 == p2)
Practice exercise: Custom Vector Class
Write a class `Vector` with `x` and `y`. Implement `__add__(self, other)` so `Vector(1,2) + Vector(3,4)` returns `Vector(4,6)`. Print `Vector(1,2) + Vector(3,4)`. Implement `__repr__` to return `f"Vector({self.x}, {self.y})"`.
Test yourself with the Module 15: Advanced OOP & Dunder Methods quiz →