Magic methods (also called dunder methods, short for double underscore) are special methods in Python that let you customize how objects behave.
These methods are called automatically when specific operations are performed on objects.
Example 1: __init__ (Constructor)
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
# Create a Book object
book = Book("1984", "George Orwell")
# Print the book details
print(book.title, book.author)Output:
1984 George OrwellThe __init__ method initializes the Book object with title and author.
Example 2: __str__ (String Representation)
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
def __str__(self):
return f"'{self.title}' by {self.author}"
# Create a Book object
book = Book("1984", "George Orwell")
print(book) # Calls __str__()Output:
'1984' by George OrwellThe __str__ method provides a human-readable string representation of the Book object when printed.
Example 3: __len__ (Length)
class Box:
def __init__(self, items):
self.items = items
def __len__(self):
return len(self.items)
# Create a Box object
box = Box([1, 2, 3])
print(len(box)) # Calls __len__()Output:
3The __len__ method enables the use of len() to get the number of items in the Box object.
Example 4: __add__ (Operator Overloading)
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
def __str__(self):
return f"({self.x}, {self.y})"
# Create two Point objects
p1 = Point(2, 3)
p2 = Point(4, 5)
p3 = p1 + p2 # Calls __add__()
print(p3)Output:
(6, 8)The __add__ method allows us to use the + operator to add two Point objects together.
Best Practices with Dunder Methods
- Use them to make objects behave like built-in types (e.g., support
len(),+, orprint()). - Always implement a string method (
__str__or__repr__) for readability and debugging. - Don’t overuse them, only override when it makes sense.
- Follow Python’s data model consistently (e.g., if you implement
__eq__, consider__hash__).
👉 Next tutorial: Python Generators