Tutorials Python Python Dunder Methods
Ch 36 / 58
Python Intermediate 14 min read Chapter 36 of 58

Python Dunder Methods

Dunder methods (double underscore, also called magic methods) are the secret engine behind Python's elegant syntax. When you write len(obj), obj + other, obj[0], or with obj:, Python calls a specific dunder method behind the scenes. By implementing these methods in your own classes, you can make them behave exactly like Python's built-in types — supporting arithmetic operators, iteration, context managers, comparison, string representation, and much more.

What you'll learn in this chapter
What dunder methods are and how Python calls them
Construction — __init__, __new__, __del__
Representation — __str__, __repr__, __format__
Arithmetic & comparison operators
Container — __len__, __getitem__, __iter__, __contains__
Context managers — __enter__ and __exit__
Advertisement

What are Dunder Methods?

Dunder methods (short for double underscore) are special methods with names surrounded by two underscores on each side: __method__. Python calls them implicitly — you never call them directly. Instead, Python maps specific syntax or built-in functions to the corresponding dunder method automatically.

Python syntax → dunder method call mapping
obj + other
▼
Python translates to
obj.__add__(other)
len(obj)
▼
obj.__len__()
str(obj) / print(obj)
▼
obj.__str__()
with obj as x:
▼
obj.__enter__() / obj.__exit__()
All Dunder Method Categories — Quick Reference
Construction
Object lifecycle
__new__ · __init__ · __del__
Representation
String & format output
__str__ · __repr__ · __bytes__ · __format__
Arithmetic
Math operators: + - * / // % **
__add__ · __sub__ · __mul__ · __truediv__ · __floordiv__ · __mod__ · __pow__ · __neg__ · __abs__
Comparison
== != < > <= >= and bool()
__eq__ · __ne__ · __lt__ · __gt__ · __le__ · __ge__ · __bool__ · __hash__
Container / Iteration
len(), [] index, in, for loop, slicing
__len__ · __getitem__ · __setitem__ · __delitem__ · __contains__ · __iter__ · __next__ · __reversed__
Context Manager
with statement
__enter__ · __exit__

Construction Dunder Methods

These methods control the lifecycle of an object — from creation through destruction.

Python — construction_dunders.py
class Singleton:
    """Demonstrates __new__ — called BEFORE __init__."""
    _instance = None

    def __new__(cls):                   # creates the object
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

    def __init__(self):                  # initialises the object
        self.value = 42

a = Singleton()
b = Singleton()
print(a is b)   # True — same object!

# ── __del__ — destructor (called when GC collects) ────
class Resource:
    def __init__(self, name):
        self.name = name
        print(f"Resource {name} created")

    def __del__(self):              # cleanup on destruction
        print(f"Resource {self.name} destroyed")

# Prefer __enter__/__exit__ (with statement) over __del__ for cleanup
r = Resource("DB")   # Resource DB created
del r               # Resource DB destroyed

# Order of calls for: obj = MyClass(args)
# 1. MyClass.__new__(MyClass)   → creates the object in memory
# 2. MyClass.__init__(obj, args) → initialises it
Method Called when Returns
__new__(cls) Creating a new instance The new object instance
__init__(self) After __new__ — initialise attributes None (must not return a value)
__del__(self) Object is garbage-collected None — avoid relying on timing

Representation Dunder Methods

These methods control how your object is displayed as a string. Always implement at minimum __repr__ — it's the fallback for everything. Add __str__ for a cleaner human-readable form.

Python — representation_dunders.py
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    # __str__ — human-readable; called by print() and str()
    def __str__(self):
        return f"({self.x}, {self.y})"

    # __repr__ — unambiguous; called by repr() and the REPL
    # Rule: should look like a constructor call that recreates the object
    def __repr__(self):
        return f"Point(x={self.x!r}, y={self.y!r})"

    # __format__ — called by f-strings and format()
    def __format__(self, spec):
        if spec == "polar":
            import math
            r     = math.sqrt(self.x**2 + self.y**2)
            theta = math.degrees(math.atan2(self.y, self.x))
            return f"r={r:.2f} θ={theta:.1f}°"
        return str(self)

p = Point(3, 4)

print(p)             # (3, 4)              ← __str__
print(str(p))         # (3, 4)              ← __str__
print(repr(p))        # Point(x=3, y=4)     ← __repr__
print(f"{p}")         # (3, 4)              ← __str__ via f-string
print(f"{p:polar}")   # r=5.00 θ=53.1°     ← __format__ custom spec

# Without __str__, print() falls back to __repr__
# Always implement __repr__ at minimum
Advertisement
K2infocom Python Masterclass & Backend Development
Master Python, Django & Backend APIs with AI
Go from absolute beginner to building production-ready REST APIs, web applications, and ML pipelines. Real projects, live mentoring in Vadodara, and placement support included.
2,400+
Students Enrolled
4.9 ⭐
Google Rating
6 Months
Full Program
100%
Placement Support
Python 3 Django & DRF FastAPI PostgreSQL Machine Learning Docker & AWS Real Projects AI Tools

Arithmetic Operator Dunder Methods

Implement arithmetic dunder methods to give your objects natural mathematical operators. Python tries __add__ first; if it returns NotImplemented, Python tries the reflected version (__radd__) on the right operand.

Python — arithmetic_dunders.py
class Vector:
    """2D vector supporting arithmetic operations."""

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):      # v1 + v2
        return Vector(self.x + other.x, self.y + other.y)

    def __sub__(self, other):      # v1 - v2
        return Vector(self.x - other.x, self.y - other.y)

    def __mul__(self, scalar):     # v * 3
        return Vector(self.x * scalar, self.y * scalar)

    def __rmul__(self, scalar):    # 3 * v  (reflected)
        return self * scalar

    def __truediv__(self, scalar): # v / 2
        return Vector(self.x / scalar, self.y / scalar)

    def __neg__(self):             # -v (unary)
        return Vector(-self.x, -self.y)

    def __abs__(self):             # abs(v) — magnitude
        return (self.x**2 + self.y**2) ** 0.5

    def __iadd__(self, other):     # v1 += v2 (in-place)
        self.x += other.x
        self.y += other.y
        return self

    def __str__(self):
        return f"Vector({self.x}, {self.y})"

v1 = Vector(3, 4)
v2 = Vector(1, 2)

print(v1 + v2)    # Vector(4, 6)
print(v1 - v2)    # Vector(2, 2)
print(v1 * 2)     # Vector(6, 8)
print(3 * v1)     # Vector(9, 12)  ← uses __rmul__
print(-v1)        # Vector(-3, -4)
print(abs(v1))    # 5.0  (3-4-5 triangle)
v1 += v2
print(v1)         # Vector(4, 6)   ← uses __iadd__

Comparison & Boolean Dunder Methods

Comparison dunder methods let your objects work with ==, !=, <, >, <=, >=, if obj:, and hash(obj). Implementing __eq__ automatically makes != work (as the negation). Use @functools.total_ordering to auto-generate the rest from just __eq__ and one of __lt__ / __gt__.

Python — comparison_dunders.py
from functools import total_ordering

@total_ordering         # auto-generates __gt__, __ge__, __le__ from __eq__ + __lt__
class Student:
    def __init__(self, name, gpa):
        self.name = name
        self.gpa  = gpa

    def __eq__(self, other):
        if not isinstance(other, Student): return NotImplemented
        return self.gpa == other.gpa

    def __lt__(self, other):
        if not isinstance(other, Student): return NotImplemented
        return self.gpa < other.gpa

    def __bool__(self):           # if student:
        return self.gpa >= 5.0    # passing grade

    def __hash__(self):           # allows use in sets and dict keys
        return hash(self.name)

    def __str__(self):
        return f"{self.name}({self.gpa})"

alice = Student("Alice", 8.5)
bob   = Student("Bob",   7.0)
carol = Student("Carol", 8.5)

print(alice > bob)        # True   ← auto from @total_ordering
print(alice == carol)     # True   ← same GPA
print(alice != bob)       # True   ← auto from __eq__

students = [alice, bob, carol]
print(sorted(students))   # [Bob(7.0), Alice(8.5), Carol(8.5)]
print(max(students))      # Alice(8.5)  or Carol(8.5)

if alice:
    print(f"{alice.name} is passing")  # ← uses __bool__

# Can use in a set because of __hash__
student_set = {alice, bob, carol}
print(len(student_set))   # 3

Container & Iteration Dunder Methods

These methods let your class behave like a sequence or collection — supporting len(), indexing (obj[i]), membership testing (x in obj), and iteration (for x in obj:).

Python — container_dunders.py
class WordBag:
    """A simple container of unique words — behaves like a sequence."""

    def __init__(self, *words):
        self._words = list(dict.fromkeys(w.lower() for w in words))

    def __len__(self):              # len(bag)
        return len(self._words)

    def __getitem__(self, index):   # bag[0], bag[1:3], bag[-1]
        return self._words[index]

    def __setitem__(self, index, value):  # bag[0] = "new"
        self._words[index] = value.lower()

    def __delitem__(self, index):   # del bag[0]
        del self._words[index]

    def __contains__(self, word):   # "python" in bag
        return word.lower() in self._words

    def __iter__(self):             # for word in bag:
        return iter(self._words)

    def __reversed__(self):         # reversed(bag)
        return iter(reversed(self._words))

    def __str__(self):
        return f"WordBag{self._words}"

bag = WordBag("Python", "is", "awesome", "Python")  # deduped

print(len(bag))           # 3
print(bag[0])             # python
print(bag[1:3])           # ['is', 'awesome']
print("python" in bag)    # True   ← __contains__
print("java"   in bag)    # False

for word in bag:           # ← __iter__
    print(word, end=" ")   # python is awesome

print(list(reversed(bag))) # ['awesome', 'is', 'python']

Context Manager Dunder Methods — __enter__ & __exit__

Implement __enter__ and __exit__ to make your class work with the with statement. This is Python's idiom for guaranteed setup and teardown — files are closed, database connections are released, locks are freed — even if an exception occurs.

Python — context_manager_dunders.py
# ── Basic context manager ─────────────────────────────
class DatabaseConnection:
    """Manages a database connection with guaranteed cleanup."""

    def __init__(self, url):
        self.url  = url
        self.conn = None

    def __enter__(self):                # called at start of with block
        print(f"Connecting to {self.url}")
        self.conn = ""        # simulate connection
        return self                        # returned as 'as' variable

    def __exit__(self, exc_type, exc_val, exc_tb):
        # called at end — exc_type is None if no exception
        if exc_type is None:
            print("Committing transaction")
        else:
            print(f"Rolling back — {exc_val}")
        print("Closing connection")
        self.conn = None
        return False            # False = don't suppress exceptions

    def query(self, sql):
        return f"Results of: {sql}"

# ── Usage ─────────────────────────────────────────────
with DatabaseConnection("postgresql://localhost/mydb") as db:
    print(db.query("SELECT * FROM users"))
# Connecting to postgresql://localhost/mydb
# Results of: SELECT * FROM users
# Committing transaction
# Closing connection

# ── contextlib.contextmanager — easier for simple cases
from contextlib import contextmanager

@contextmanager
def timer(label):
    import time
    start = time.perf_counter()
    try:
        yield                    # code inside 'with' runs here
    finally:
        elapsed = time.perf_counter() - start
        print(f"{label}: {elapsed:.4f}s")

with timer("List comp"):
    result = [i**2 for i in range(100000)]
__exit__ signature explained __exit__(self, exc_type, exc_val, exc_tb) receives exception information if one occurred in the with block. Return True to suppress the exception (rarely correct); return False or None to let it propagate.

Practice Python Online — Free Compilers

Don't want to install anything yet? Practice all dunder method examples from this chapter directly in your browser with these free Python environments.

▶
Online Python 3 Compiler
Write, run and debug Python code in your browser. No installation required. Test every dunder method example instantly.
Open Compiler
Replit
Full IDE online
Google Colab
Free GPU notebooks
JupyterLite
Notebooks in browser
Programiz
Beginner-friendly
Chapter Summary
  • Dunder methods (__method__) are called implicitly by Python syntax and built-in functions — never call them directly.
  • Construction: __new__ creates the object, __init__ initialises it. __del__ is a destructor but don't rely on its timing.
  • Representation: always implement __repr__ (unambiguous, developer-facing). Add __str__ for a cleaner human-readable form. __format__ enables custom format specs.
  • Arithmetic: __add__, __sub__, __mul__, __truediv__, __neg__, __abs__. Reflected versions (__radd__, etc.) handle scalar + obj. In-place (__iadd__) handles obj +=.
  • Comparison: __eq__, __lt__, __bool__, __hash__. Use @functools.total_ordering to auto-generate the rest from __eq__ + one ordering method.
  • Container protocol: __len__, __getitem__, __setitem__, __delitem__, __contains__, __iter__, __reversed__ — make your class behave like a list or dict.
  • Context managers: __enter__ sets up the resource (returned as as x); __exit__ tears it down — always called even if an exception occurs.
  • Return NotImplemented (not NotImplementedError) from comparison dunders when the type is unknown — lets Python try the reflected operation.
Free Resource
Download our Python Dunder Methods Cheat Sheet
All categories — construction, representation, arithmetic, comparison, container & context managers — one printable page.
Get Sheet
Advertisement
Quick Check — Test Your Understanding
Question & Answer
✓ Answer

__str__ returns a human-readable string aimed at end users. Called by print(), str(), and f-strings.

__repr__ returns an unambiguous developer/debug string. Called by the REPL, repr(), and inside containers (print([obj]) calls __repr__ on each element). The ideal __repr__ looks like a constructor call that recreates the object: Point(x=3, y=4).

If only __repr__ is defined, it's used for everything. Always implement __repr__ at minimum.

✓ Answer

__enter__ and __exit__ implement the context manager protocol, enabling use of the with statement.

  • __enter__(self) — called at the start of the with block. Sets up the resource. Returns the value bound to the as variable.
  • __exit__(self, exc_type, exc_val, exc_tb) — always called at the end, even if an exception occurred. Tears down the resource. Return True to suppress exceptions, False to propagate.
✓ Answer

__new__(cls) is the constructor — it creates and returns the new object instance. It receives the class as its first argument and must return the new instance. Called before __init__.

__init__(self) is the initialiser — it sets up the newly created instance's attributes. It receives the new object as self and must return None. In most classes you only need __init__. Override __new__ only for advanced patterns like Singleton or immutable types.

✓ Answer

__len__(self) should return a non-negative integer representing the "length" or "size" of the object. It's called by len(obj).

Python also uses it for truthiness: if __bool__ is not defined, Python calls __len__ — an object with length 0 is falsy, anything else is truthy.

class Stack:
    def __init__(self): self._items = []
    def __len__(self): return len(self._items)

s = Stack()
print(bool(s))   # False — empty stack (len=0)
✓ Answer

When a comparison dunder (like __eq__) receives an object of an unknown or unsupported type, it should return the singleton NotImplemented (not raise NotImplementedError).

Returning NotImplemented tells Python: "I don't know how to compare with this type — try the other operand's reflected method." Python will then try other.__eq__(self). If both return NotImplemented, Python falls back to identity comparison (is).

def __eq__(self, other):
    if not isinstance(other, MyClass):
        return NotImplemented  # ← correct
    return self.value == other.value
MCQ 1 of 3
Which dunder method does Python call when you use len(obj)?
MCQ 2 of 3
Which pair of dunder methods enables the with statement for a class?
MCQ 3 of 3
Which decorator auto-generates comparison dunder methods from just __eq__ and __lt__?

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel