Python Dunder Methods (Magic Methods)

A complete mental-model-based guide with real code examples

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: