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 MethodTriggered ByPurpose
__init__Object creation: obj = Class()Constructor; initialise instance attributes
__str__str(obj) or print(obj)Human-readable string representation
__repr__repr(obj) or in consoleOfficial string representation for debugging
__len__len(obj)Define object’s length
__getitem__obj[key]Indexing behavior
__setitem__obj[key] = valueSetting items using index
__delitem__del obj[key]Deleting items using index
__iter__for item in objMakes 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. operatorsDefine 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: