Dunder methods (short for “double underscore” methods) in Python are special methods that have names starting and ending with double underscore, like __init__
, __str__
, __len__
, etc.
You don’t need to call them directly (you can however) - Python calls them for you in response to specific syntax or built-in functions.
Common dunder methods
Dunder Method | Triggered By | Purpose |
---|---|---|
__init__ | Object creation: obj = Class() | Constructor; initialise instance attributes |
__str__ | str(obj) or print(obj) | Human-readable string representation |
__repr__ | repr(obj) or in console | Official string representation for debugging |
__len__ | len(obj) | Define object’s length |
__getitem__ | obj[key] | Indexing behavior |
__setitem__ | obj[key] = value | Setting items using index |
__delitem__ | del obj[key] | Deleting items using index |
__iter__ | for item in obj | Makes an object iterable |
__next__ | next(iterator) | Defines iteration steps |
__eq__ , __lt__ , etc. | Comparisons like == , < , > | Define how objects compare |
__call__ | obj() | Make an object behave like a function |
__add__ , __sub__ , etc. | + , - , etc. operators | Define arithmetic behavior |
Overriding dunder methods
You are suppose to override dunder methods to customise your classes behaviours.
- Set up initialisation (
__init__
) - Customize string output (
__str__
) - Enable iteration (
__iter__
,__next__
) - Allow indexing (
__getitem__
) - Control comparisons (
__eq__
,__lt__
, etc.) - Override operators (
__add__
,__mul__
, etc.)
Example 1
class Book:
def __init__(self, title):
self.title = title
def __str__(self):
return f"Book: {self.title}"
def __len__(self):
return len(self.title)
book = Book("Python Magic")
print(book)
print(len(book))
Book Magic
13
Example 2
class Box:
def __init__(self, volume):
self.volume = volume
def __eq__(self, other):
return self.volume == other.volume
def __lt__(self, other):
return self.volume < other.volume
b1 = total_ordering(Box)(10)
b2 = total_ordering(Box)(20)
assert b1 < b2
assert b1 <= b2
assert not b1 > b2
> Program exited with code 0
Back to parent page: