Dunder Methods & the Python Data Model
Lesson 4 of 6 · View course roadmap
Learn the idea
Why does len("abc") work? Because str implements __len__. Python's operators and built-ins are a thin layer over dunder (double-underscore) methods — implement them and your own classes plug straight into the language:
__repr__— how the object prints (aim for something a developer could paste back into code)__add__— powersa + b__eq__— powers==(by default Python compares identity, not value!)__len__,__getitem__,__contains__— make objects sliceable, iterable andin-testable
This is called the data model, and it's the most Pythonic idea in the language: instead of inventing .equals() or .plus() methods, you teach your objects to speak Python's native vocabulary.
Where you'll use this
pathlib overloads / to join paths, NumPy overloads every operator for arrays, Django models compare by value — Python's most loved libraries feel native precisely because they implement the data model instead of inventing method names.
Common mistakes
- Defining
__eq__without thinking about__hash__— Python sets__hash__to None, and your objects can no longer live in sets or dict keys. Implement both or use @dataclass(frozen=True). - Returning a plain tuple from
__add__instead of a new instance of your class — addition should stay closed over the type. - Writing
__repr__that hides information: aim for eval-able output like Vector(4, 6), not '<Vector object>'.
Pro tip
Implement __repr__ on every class you write, first thing. Debugging a list of '
Try it yourself
The lesson example is loaded and ready — press Run, then change something and run it again. Breaking it is part of learning. Want a clean slate? Tap “New blank”.
Output appears here…
Pass the challenge +45 XP
Build a Vector class with x and y. Implement __repr__ returning Vector(x, y), __add__ for coordinate-wise addition, and __eq__ for value equality. Print Vector(1, 2) + Vector(3, 4), then print Vector(1, 2) == Vector(1, 2).
Vector(4, 6) True
__repr__ returns f"Vector({self.x}, {self.y})"; __add__ returns Vector(self.x + other.x, self.y + other.y); __eq__ compares both coordinates.
class Vector:
def __init__(self, x, y):
self.x = x
self.y = 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)
def __eq__(self, other):
return self.x == other.x and self.y == other.y
print(Vector(1, 2) + Vector(3, 4))
print(Vector(1, 2) == Vector(1, 2))
Run your code to check it…
Check your understanding
Your notes (saved on this device)
Tip: use ← and → to move between lessons, ⌘K to search everything.