What are Dunder Methods?
Dunder methods (Double UNDERscore methods) are special Python methods
written as __method__.
Python automatically calls them to define how objects behave.
Example: when you use +, Python internally calls __add__().
Common Dunder Methods List
| Category | Dunder Method | Purpose |
|---|---|---|
| Object Creation | __init__ | Initialize object |
| String Representation | __str__ | Human readable output |
| String Representation | __repr__ | Developer representation |
| Length | __len__ | Supports len() |
| Indexing | __getitem__ | Supports obj[index] |
| Calling | __call__ | Call object like function |
| Operator | __add__ | Supports + operator |
| Comparison | __eq__ | Supports == |
| Context Manager | __enter__ | Enter with-block |
| Context Manager | __exit__ | Exit with-block |
| Import System | __all__ | Controls import * |
| Execution | __name__ | Module execution check |
1️⃣ __init__ – Object Initialization
Called automatically when an object is created.
class Student:
def __init__(self, name):
self.name = name
s = Student("Aman")
print(s.name)
2️⃣ __str__ – Printable Output
Defines what print(object) shows.
class Student:
def __str__(self):
return "Student Object"
print(Student())
3️⃣ __len__ – Length Support
class Course:
def __len__(self):
return 5
print(len(Course()))
4️⃣ __getitem__ – Indexing
class Marks:
def __getitem__(self, index):
return [90, 80, 70][index]
m = Marks()
print(m[1])
5️⃣ __call__ – Callable Objects
class Logger:
def __call__(self):
print("Called like a function")
log = Logger()
log()
6️⃣ __add__ – Operator Overloading
class Number:
def __init__(self, value):
self.value = value
def __add__(self, other):
return self.value + other.value
print(Number(5) + Number(10))
7️⃣ __enter__ & __exit__ – Context Manager
class FileManager:
def __enter__(self):
print("Entering")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("Exiting")
with FileManager():
print("Inside with block")
Mental Model to Remember
Think of dunder methods as hooks that Python automatically uses. You don’t call them directly — Python calls them when needed.
Example mental shortcut:
print(obj)→__str__obj + obj→__add__len(obj)→__len__