Magic / Dunder Methods
Dunder (double underscore) methods like __init__, __str__, __repr__, __len__, __add__ customize how objects behave with Python operators and built-in functions.
15 min•By Priygop Team•Updated 2026
Magic Methods
Magic Methods
class Book:
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages
def __str__(self): # print() friendly
return f"'{self.title}' by {self.author}"
def __repr__(self): # developer friendly
return f"Book('{self.title}', '{self.author}', {self.pages})"
def __len__(self):
return self.pages
def __eq__(self, other):
return self.title == other.title and self.author == other.author
def __lt__(self, other):
return self.pages < other.pages
def __contains__(self, word):
return word.lower() in self.title.lower()
b1 = Book("Python Crash Course", "Eric Matthes", 544)
b2 = Book("Automate the Boring Stuff", "Al Sweigart", 592)
print(b1) # __str__
print(repr(b1)) # __repr__
print(len(b1)) # __len__: 544
print(b1 < b2) # __lt__: True
print("Python" in b1) # __contains__: True
# Sortable!
books = [b2, b1]
books.sort()
for b in books:
print(f" {b} ({len(b)} pages)")Tip
Tip
Implement __str__ for user-friendly output and __repr__ for debugging. __repr__ should ideally be valid Python to recreate the object.
Diagram
Loading diagram…
__str__ for users, __repr__ for developers. __getitem__ + __iter__ make objects behave like collections.
Common Mistake
Warning
If you define __eq__ but not __hash__, your objects can't be used in sets or as dict keys. Define both together.
Practice Task
Note
(1) Create a Book class with __str__, __repr__, __len__, __lt__. (2) Sort a list of books. (3) Use 'in' operator with __contains__.