01 / 20
__ fn __

Special Methods
Dunder Methods

Discover how Python's double-underscore methods let your custom objects behave like built-in types: printable, measurable, and debuggable.

Python

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?

Readable Output
Without __str__, printing an object gives an ugly memory address like <__main__.Dog at 0x7f>.
Built-in Integration
Functions like len(), str(), and repr() all rely on dunder methods to work with your objects.
Pythonic Code
Dunder methods make your classes feel natural. Instead of obj.get_length(), you just write len(obj).

The Big Picture

print(obj) repr(obj) len(obj) calls calls calls __str__(self) __repr__(self) __len__(self) returns returns returns str str int Python's built-in functions delegate to your dunder methods

The Core Rule

1
__str__(self) must return a string. It defines the human-friendly display.
2
__repr__(self) must return a string. It defines the developer-friendly, unambiguous representation.
3
__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.

Python
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.

Python
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.

Python
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

1
Identify the need. Ask: will users print this object? Check its length? Debug it in a console?
2
Define __repr__ first. It serves as the fallback for __str__ and is essential for debugging.
3
Add __str__ if needed. Only if you want a different, simpler output for end users.
4
Add __len__ when your object is a container. If it holds a collection of items, define this method.
5
Test with built-in functions. Call print(), repr(), and len() to verify your methods work.

Example: Student Class

Python
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})"
print(s)
Alice (Grade 10)
repr(s)
Student('Alice', 10)

Example: ShoppingCart Class

Python
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})"
len(cart)
3
print(cart)
Cart with 3 items

All Three Together

Python
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)
Output
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

✕ Printing Instead of Returning
Writing print(...) inside __str__ instead of return. The method must return a string, not print it.
✕ Returning a Non-String
Having __str__ or __repr__ return an integer or list. Both must always return a string.
✕ Forgetting self
Defining 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?

Question 2 of 5

Which built-in function triggers __len__?

Question 3 of 5

If a class defines __repr__ but not __str__, what happens when you call print(obj)?

Question 4 of 5

What is wrong with this code?

class Dog:
    def __str__(self):
        print("Woof!")

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)