Special Methods
Dunder Methods
Discover how Python's double-underscore methods let your custom objects behave like built-in types: printable, measurable, and debuggable.
What Are Dunder Methods?
"Dunder" stands for double underscore. These are special method names that start and end with two underscores, like __init__, __str__, and __len__. Python calls them automatically in response to certain operations.
Dunder methods are also called magic methods or special methods. They are the hooks that let your classes integrate with Python's built-in syntax and functions.
Why Do They Matter?
__str__, printing an object gives an ugly memory address like <__main__.Dog at 0x7f>.len(), str(), and repr() all rely on dunder methods to work with your objects.obj.get_length(), you just write len(obj).The Big Picture
The Core Rule
__str__(self) must return a string. It defines the human-friendly display.__repr__(self) must return a string. It defines the developer-friendly, unambiguous representation.__len__(self) must return a non-negative integer. It defines what "length" means for your object.__str__: The Friendly Face
__str__ is called when you use print() or str() on an object. Its job is to return a nice, readable string for end users.
class Book: def __init__(self, title, author): self.title = title self.author = author def __str__(self): return f"{self.title} by {self.author}" b = Book("1984", "George Orwell") print(b) # 1984 by George Orwell
__repr__: The Developer View
__repr__ is called when you inspect an object in the console, or when repr() is used. Its goal: produce an unambiguous string that could recreate the object.
class Book: def __init__(self, title, author): self.title = title self.author = author def __repr__(self): return f"Book({self.title!r}, {self.author!r})" b = Book("1984", "George Orwell") b # Book('1984', 'George Orwell')
__str__ vs __repr__
| __str__ | __repr__ | |
|---|---|---|
| Audience | End users | Developers |
| Goal | Readable, friendly | Unambiguous, precise |
| Triggered by | print(), str() | repr(), console |
| Fallback | Falls back to __repr__ | Default memory address |
| Example output | 1984 by Orwell | Book('1984', 'Orwell') |
__len__: Giving Objects Size
__len__ is called when you use len() on an object. It must return a non-negative integer.
class Playlist: def __init__(self, songs): self.songs = songs def __len__(self): return len(self.songs) p = Playlist(["Song A", "Song B", "Song C"]) print(len(p)) # 3
How to Apply Dunder Methods
__repr__ first. It serves as the fallback for __str__ and is essential for debugging.__str__ if needed. Only if you want a different, simpler output for end users.__len__ when your object is a container. If it holds a collection of items, define this method.print(), repr(), and len() to verify your methods work.Example: Student Class
class Student: def __init__(self, name, grade): self.name = name self.grade = grade def __str__(self): return f"{self.name} (Grade {self.grade})" def __repr__(self): return f"Student({self.name!r}, {self.grade!r})"
Example: ShoppingCart Class
class ShoppingCart: def __init__(self): self.items = [] def add(self, item): self.items.append(item) def __len__(self): return len(self.items) def __str__(self): return f"Cart with {len(self)} items" def __repr__(self): return f"ShoppingCart(items={self.items!r})"
All Three Together
class Team: def __init__(self, name, members): self.name = name self.members = members def __str__(self): return f"Team {self.name} ({len(self)} members)" def __repr__(self): return f"Team({self.name!r}, {self.members!r})" def __len__(self): return len(self.members)
t = Team("Rockets", ["Ali", "Bo", "Cal"]) print(t) # Team Rockets (3 members) repr(t) # Team('Rockets', ['Ali', 'Bo', 'Cal']) len(t) # 3 bool(t) # True (len > 0)
Common Mistakes
print(...) inside __str__ instead of return. The method must return a string, not print it.__str__ or __repr__ return an integer or list. Both must always return a string.def __len__(): without self. All dunder methods need self as the first parameter.Summary Table
| Method | Triggered By | Must Return | Purpose |
|---|---|---|---|
| __str__ | print(), str() | str | Human-friendly display |
| __repr__ | repr(), console | str | Developer debugging |
| __len__ | len(), bool() | int (\( \ge 0 \)) | Object size/count |
Question 1 of 5
What does the term "dunder" stand for in Python?
__str__.Question 2 of 5
Which built-in function triggers __len__?
obj.__len__(). It must return a non-negative integer.Question 3 of 5
If a class defines __repr__ but not __str__, what happens when you call print(obj)?
__repr__ when __str__ is not defined. This is why defining __repr__ first is a good practice.Question 4 of 5
What is wrong with this code?
class Dog: def __str__(self): print("Woof!")
__str__ must return a string. Using print() inside it will print the text but then return None, causing a TypeError when Python tries to use the result.Question 5 of 5
Given this class, what does bool(Bag([])) evaluate to?
class Bag: def __init__(self, items): self.items = items def __len__(self): return len(self.items)
Bag([]) has an empty list, so __len__ returns 0. In a boolean context, an object with len() == 0 is falsy, so bool(Bag([])) evaluates to False.