Last modified: Dec 01, 2026
Python Dunder Methods List
Dunder methods are special Python methods with double underscores on both sides. They let your objects work with built-in syntax. Think of them as hooks into Python itself.
You do not call most dunder methods directly. Python calls them for you. When you write len(obj), Python runs __len__. When you use +, Python runs __add__.
This guide walks through the most useful dunder methods. Each one comes with a short example and output. By the end, you will know which method to reach for and why. If you want a wider reference, keep the full list of Python magic methods open in another tab.
Why Dunder Methods Matter
Dunder methods make your classes feel native. A custom object can support printing, comparison, looping, and math. It all happens through a small set of well-known names.
They also keep your code clean. Instead of calling obj.get_length(), you write len(obj). Instead of obj.add(other), you write obj + other. The syntax reads naturally.
Before diving in, make sure you are comfortable with classes in general. If classes are new to you, start with Python class basics and come back here.
Object Lifecycle Methods
These methods control how an object is created and destroyed. They run at key moments in an object's life.
__init__
The initializer sets up a new object. Python calls __init__ right after the object is created. This is where you assign starting values.
class Book:
def __init__(self, title, pages):
self.title = title # store the title
self.pages = pages # store the page count
book = Book("Python Basics", 250)
print(book.title, book.pages)
Python Basics 250
If you pass values into your class, you are already using this method. For a deeper look, see this guide on a Python class with arguments.
__str__ and __repr__
These two methods control how your object looks as text. __str__ is for users. __repr__ is for developers and debugging.
class Book:
def __init__(self, title):
self.title = title
def __str__(self):
return f"Book: {self.title}" # friendly text
def __repr__(self):
return f"Book('{self.title}')" # precise text
b = Book("Python Basics")
print(str(b))
print(repr(b))
Book: Python Basics
Book('Python Basics')
A good rule is simple. Always write __repr__. Add __str__ when users will see the output.
Length and Truthiness Methods
These methods connect your object to built-in checks. They make conditions and size checks work on custom types.
__len__
Python calls __len__ when you use len() on your object. It must return a non-negative integer.
class Playlist:
def __init__(self, songs):
self.songs = songs
def __len__(self):
return len(self.songs) # delegate to the list
p = Playlist(["Song A", "Song B", "Song C"])
print(len(p))
3
__bool__
Python calls __bool__ when it needs a true or false value. It is used in if statements and bool() calls. It must return True or False.
class Playlist:
def __init__(self, songs):
self.songs = songs
def __bool__(self):
return len(self.songs) > 0 # empty means False
print(bool(Playlist([])))
print(bool(Playlist(["Song A"])))
False
True
Comparison Methods
Comparison dunders let your objects use ==, <, and other operators. Python calls the matching method for each operator.
The main ones are __eq__, __lt__, __le__, __gt__, and __ge__. You often only need __eq__ and __lt__.
class Version:
def __init__(self, number):
self.number = number
def __eq__(self, other):
return self.number == other.number # equality check
def __lt__(self, other):
return self.number < other.number # less-than check
v1 = Version(2)
v2 = Version(3)
print(v1 == v2)
print(v1 < v2)
False
True
Be careful with __eq__. Once you define it, Python stops using the default identity check. Two different objects can now be equal.
Arithmetic Methods
Arithmetic dunders let your objects support math operators. Each operator maps to a specific method name.
The common ones include __add__, __sub__, __mul__, and __truediv__. They power +, -, *, and /.
class Money:
def __init__(self, amount):
self.amount = amount
def __add__(self, other):
return Money(self.amount + other.amount) # add amounts
def __str__(self):
return f"${self.amount}"
total = Money(10) + Money(25)
print(total)
$35
Many of these methods also have an in-place version, like __iadd__ for +=. Python falls back to the regular method if the in-place one is missing.
Container Methods
Container dunders make your object behave like a list or dictionary. They support indexing, looping, and membership checks.
The key methods are __getitem__ for indexing, __setitem__ for assignment, __contains__ for membership, and __iter__ for looping.
class Bag:
def __init__(self, items):
self.items = items
def __getitem__(self, index):
return self.items[index] # support obj[index]
def __contains__(self, value):
return value in self.items # support "in"
bag = Bag(["apple", "pear", "plum"])
print(bag[1])
print("pear" in bag)
pear
True
If you define __getitem__ but not __iter__, Python can still loop over your object. It uses indexing until it hits an IndexError.
Context Manager Methods
These methods let your object work with the with statement. They handle setup and cleanup safely.
The pair is __enter__ and __exit__. Setup goes in __enter__. Cleanup goes in __exit__.
class Resource:
def __enter__(self):
print("Opening resource") # setup step
return self
def __exit__(self, exc_type, exc, tb):
print("Closing resource") # cleanup step
with Resource():
print("Working inside block")
Opening resource
Working inside block
Closing resource
This pattern is common for files, network connections, and locks. It guarantees cleanup even when errors happen.
Attribute Access Methods
These dunders control how attributes are read, set, and deleted. They are powerful, but easy to misuse.
The main ones are __getattr__ for missing attributes, __setattr__ for assignment, and __delattr__ for deletion.
class Config:
def __init__(self):
self.data = {"debug": True}
def __getattr__(self, name):
return self.data.get(name, None) # fallback lookup
c = Config()
print(c.debug)
print(c.missing)
True
None
Use these methods sparingly. Simple attributes are easier to read. For normal attribute handling, see this guide on Python class methods and attributes.
Callable Objects
The __call__ method makes an object callable like a function. You invoke it with parentheses.
class Multiplier:
def __init__(self, factor):
self.factor = factor
def __call__(self, value):
return value * self.factor # run like a function
double = Multiplier(2)
print(double(10))
20
Callable objects are useful for stateful functions. They remember data between calls.
Quick Reference Table
Here is a short summary of the methods covered above. Keep it nearby as a cheat sheet.
- Object lifecycle:
__init__,__del__ - Text output:
__str__,__repr__ - Size and truth:
__len__,__bool__ - Comparison:
__eq__,__lt__,__le__,__gt__,__ge__ - Arithmetic:
__add__,__sub__,__mul__,__truediv__ - Containers:
__getitem__,__setitem__,__contains__,__iter__ - Context managers:
__enter__,__exit__ - Attributes:
__getattr__,__setattr__,__delattr__ - Callable:
__call__
Best Practices
Start small. Add dunder methods only when they make your code clearer. A class with no dunders is often fine.
Keep each method short and focused. Delegate real work to normal methods. This keeps your class easy to test.
Always write __repr__ for debugging. It saves time when you print objects in the console.
Do not overload operators in confusing ways. If + means something odd for your type, use a named method instead.
Finally, read the official Python data model docs. They list every dunder method and its exact behavior. That reference is the best source when you need details.
Conclusion
Dunder methods connect your classes to Python's built-in syntax. They cover creation, printing, comparison, math, containers, and more. You do not need all of them. You only need the ones that fit your object.
Start with __init__ and __repr__. Then add others as your class grows. Each addition should make your code more readable, not more clever. With a little practice, dunder methods will feel like a natural part of your Python toolkit.