Magic Methods and Operator Overloading
Integrate custom classes into Python's native syntax using dunder magic methods. Master string representations (__str__, __repr__), operator overloading, and container protocols.
Have you ever wondered how Python handles basic everyday operations like:
len([1, 2, 3])"Hello" + " World"user in user_listprint(my_object)
In many other languages, operators like + or functions like len() are rigid compiler commands reserved exclusively for built-in primitive types.
In Python, however, there are no privileged data types.
Every single built-in operator and standard function in Python is wired directly to a special method name enclosed in double underscores:
__init__, __str__, __repr__, __add__, __eq__, __len__.
Because these methods are wrapped in double underscores, the Python community affectionately calls them Dunder Methods (short for Double Underscore) or Magic Methods.
By implementing these methods on your own custom classes, you allow your objects to integrate seamlessly with Python’s native syntax!
1. Object Representation: __repr__ and __str__
Look at what happens if you print an instance of a class that does not implement any representation methods:
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
book = Book("Atomic Habits", "James Clear")
print(book)
Output:
<__main__.Book object at 0x7fa284091a90>
That ugly string is merely the class name and its physical hexadecimal memory address in RAM. It tells human users nothing!
The Solution: __str__ vs __repr__
Python provides two distinct representation dunders:
__str__(self): Designed for end users. Returns a warm, friendly, readable display string. Called byprint(obj)andstr(obj).__repr__(self): Designed for developers and debuggers. Returns an explicit, unambiguous representation of the object. Called in terminal REPLs and debug logs.
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
def __str__(self):
# Friendly for human readers
return f"'{self.title}' by {self.author}"
def __repr__(self):
# Unambiguous: shows how to recreate the exact object in code!
return f"Book(title={self.title!r}, author={self.author!r})"
book = Book("Atomic Habits", "James Clear")
# print() calls __str__ automatically:
print("Friendly display:", book)
# repr() reveals the exact technical construction:
print("Developer representation:", repr(book))
Output:
Friendly display: 'Atomic Habits' by James Clear
Developer representation: Book(title='Atomic Habits', author='James Clear')
[!TIP] Always implement
__repr__first! If__str__is omitted, Python automatically falls back to calling__repr__.
2. Operator Overloading: Arithmetic
What if you want to add two 2D mathematical vectors together with v1 + v2?
In Python, typing a + b causes Python to invoke a.__add__(b):
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"Vector({self.x}, {self.y})"
# Overload the addition operator (+)
def __add__(self, other):
if not isinstance(other, Vector):
return NotImplemented
return Vector(self.x + other.x, self.y + other.y)
# Overload multiplication (*) by a scalar scalar number
def __mul__(self, scalar):
return Vector(self.x * scalar, self.y * scalar)
v1 = Vector(2, 5)
v2 = Vector(3, 1)
v3 = v1 + v2 # Triggers v1.__add__(v2)!
scaled = v1 * 3 # Triggers v1.__mul__(3)!
print("Sum: ", v3) # Vector(5, 6)
print("Scaled:", scaled) # Vector(6, 15)
Common Arithmetic Magic Methods
__add__(self, other):+__sub__(self, other):-__mul__(self, other):*__truediv__(self, other):/__floordiv__(self, other)://
3. Comparison Magic: __eq__ and __lt__
By default, testing obj1 == obj2 compares memory IDs (id(obj1) == id(obj2)). Two distinct objects with identical contents will evaluate to False!
Implement __eq__ to define what equality means for your data:
class Product:
def __init__(self, sku, name, price):
self.sku = sku
self.name = name
self.price = price
# Two products are identical if their SKU matches
def __eq__(self, other):
if isinstance(other, Product):
return self.sku == other.sku
return False
# Define less-than (<) for automatic sorting by price
def __lt__(self, other):
if isinstance(other, Product):
return self.price < other.price
return NotImplemented
p1 = Product("SKU-100", "Mechanical Keyboard", 89.99)
p2 = Product("SKU-100", "Mechanical Keyboard (Restock)", 89.99)
p3 = Product("SKU-200", "Wireless Mouse", 29.99)
print("Are p1 and p2 equal?", p1 == p2) # True (Same SKU!)
# Implementing __lt__ enables automatic sorting!
catalog = [p1, p3]
sorted_catalog = sorted(catalog)
print("Cheapest item first:", [item.name for item in sorted_catalog])
# ['Wireless Mouse', 'Mechanical Keyboard']
4. Emulating Container Types: __len__ and __getitem__
You can make your custom classes behave like lists or dicts:
class Team:
def __init__(self, name):
self.name = name
self.members = []
def add_member(self, person):
self.members.append(person)
# Enables len(team)
def __len__(self):
return len(self.members)
# Enables bracket indexing: team[0]
def __getitem__(self, index):
return self.members[index]
# Enables membership check: "Alice" in team
def __contains__(self, person):
return person in self.members
team = Team("Backend Core")
team.add_member("Alice")
team.add_member("Bob")
team.add_member("Charlie")
print("Team size: ", len(team)) # 3
print("Team captain: ", team[0]) # Alice
print("Is Bob on team? ", "Bob" in team) # True
# Magic: Implementing __len__ and __getitem__ makes your object iterable in for loops!
print("Roster:")
for member in team:
print(f" - {member}")
Output:
Team size: 3
Team captain: Alice
Is Bob on team? True
Roster:
- Alice
- Bob
- Charlie
Notice that without writing an iterator from scratch, Python’s for loop worked automatically because team implemented __getitem__!
Summary & What’s Next
- Dunder (magic) methods start and end with double underscores (
__method__). - Implement
__repr__for clear debugging and__str__for friendly display. - Overload mathematical operators using
__add__,__sub__, and__mul__. - Overload equality using
__eq__and comparison using__lt__. - Enable Python container protocols using
__len__,__getitem__, and__contains__.
What if you are architecting a large application and need to guarantee that every subclass implements a specific set of methods before it can even be instantiated? Learn how to enforce interface contracts using abstract-classes.