Operator Overloading
Make +, ==, print(), and len() work with your own classes using special "dunder" methods.
What Are Dunder Methods?
"Dunder" stands for double underscore. Methods like __init__, __str__, and __add__ are special methods that Python calls behind the scenes when you use operators or built-in functions.
When you write a + b, Python actually calls a.__add__(b). By defining these methods in your class, you control how operators behave with your objects.
__str__: How print() Displays Your Object
Without __str__, printing an object gives you something ugly like <__main__.Product object at 0x...>. Define __str__ to control that.
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def __str__(self):
return f"{self.name}: ${self.price:.2f}"
p = Product("Laptop", 999)
print(p) # Laptop: $999.00
__add__: Make + Work
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __str__(self):
return f"({self.x}, {self.y})"
v1 = Vector(1, 2)
v2 = Vector(3, 4)
print(v1 + v2) # (4, 6)
How it works: When Python sees v1 + v2, it calls v1.__add__(v2). Our method creates and returns a new Vector with the combined values.
__eq__ and __lt__: Comparison Operators
class Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade
def __eq__(self, other):
return self.grade == other.grade
def __lt__(self, other):
return self.grade < other.grade
def __str__(self):
return f"{self.name} (grade: {self.grade})"
s1 = Student("Alice", 92)
s2 = Student("Bob", 85)
s3 = Student("Carol", 92)
print(s1 == s3) # True (same grade)
print(s2 < s1) # True (85 < 92)
# Sorting works automatically with __lt__
students = [s1, s2, s3]
students.sort()
for s in students:
print(s)
__len__: Make len() Work
class Playlist:
def __init__(self, name):
self.name = name
self.songs = []
def add(self, song):
self.songs.append(song)
def __len__(self):
return len(self.songs)
p = Playlist("Road Trip")
p.add("Bohemian Rhapsody")
p.add("Hotel California")
print(len(p)) # 2
Common Dunder Methods
| Method | Triggered By | Purpose |
|---|---|---|
| __str__ | print(obj), str(obj) | Human-readable string |
| __repr__ | repr(obj), debugger | Developer-readable string |
| __add__ | a + b | Addition |
| __eq__ | a == b | Equality check |
| __lt__ | a < b, sorting | Less-than comparison |
| __len__ | len(obj) | Length / size |
Best Practices
- Always define
__str__for any class you might print -- it makes debugging so much easier. - Return a new object from
__add__rather than modifyingself-- just like how1 + 2gives a new number. - Only overload operators when the behavior is intuitive (adding vectors makes sense; adding users does not).
Common Mistakes
- Forgetting to return a value from
__add__-- without a return, the result isNone. - Confusing
__str__(for users) with__repr__(for developers). Define both when appropriate. - Overloading operators in ways that are confusing or unexpected to other programmers.
Practice Exercises
Exercise 1: Money Class
Create a Money class with __add__, __str__, and __eq__. Adding two Money objects should return a new one with the combined amounts.
Exercise 2: Shopping Cart
Create a Cart class where len(cart) returns the number of items and print(cart) shows all items.
Exercise 3: Temperature
Create a Temperature class with __lt__, __eq__, and __str__. Create a list of temperatures and sort them.
Summary
- Operator overloading lets you define how +, ==, <, print(), and len() work with your classes.
- Dunder methods (__str__, __add__, __eq__, __lt__, __len__) are the mechanism behind it.
- Always return a new object from __add__ and keep overloads intuitive.
- This is another form of polymorphism -- same operator, different behavior per class.