← Reference

dunder-methods

Python dunder-methods reference.

__add__ / __radd__ / __iadd__

Implement the + and += operators on your custom classes with __add__, __radd__, and __iadd__.

def __add__(self, other)

__bool__

Control how your objects evaluate in boolean context — Python's __bool__ method explained with practical examples.

__call__

Make instances callable like functions

def __call__(self, ...)

__class_getitem__

A class method that handles subscription on the class itself, enabling generic type expressions like MyClass[T].

__class_getitem__(cls, item)

__contains__

Implement the __contains__ method to define custom membership test behavior for the in operator in Python.

__contains__(item)

__del__

Understand Python's __del__ destructor, its relationship to garbage collection, and why to avoid it in modern Python 3.

__delitem__

Learn how to implement __delitem__ to enable custom deletion behavior with the del keyword in your Python classes.

def __delitem__(self, key)

__enter__ / __exit__

A complete reference for Python's context manager protocol, covering __enter__ and __exit__ dunder methods, exception handling, and practical examples.

__eq__

Learn how to define equality comparison for your Python objects using __eq__ and __ne__ dunder methods.

__eq__(self, other)

__getattr__ / __getattribute__

Control Python attribute access with __getattribute__ (every lookup) and __getattr__ (missing attributes only).

__hash__

Define the hash value for your Python objects so they can be used in sets and as dictionary keys.

__hash__(self)

__mul__ / __rmul__ / __imul__

Python's three multiplication dunder methods — when each is called, how NotImplemented works, and how __imul__ differs for mutables.

__new__

Creates and returns a new class instance before __init__ is called. Used to implement singletons, immutable objects, and factory patterns.

def __new__(cls, *args, **kwargs)

__next__

Learn how to implement the __next__ method to create custom iterators in Python. Complete guide with examples.

__next__(self)

__setattr__ and __delattr__

Control attribute assignment and deletion with Python's __setattr__ and __delattr__ dunder methods.

__setitem__

Python's __setitem__ method enables subscript assignment. Learn how to implement key-value setting in custom classes.

__setitem__(self, key, value)

__str__

Python's __str__ magic method explained with practical examples

__str__(self)

__sub__ / __rsub__ / __isub__

Implement subtraction in Python classes: __sub__ for a - b, __rsub__ for reversed b - a, and __isub__ for in-place a -= b.

__sub__(self, other)

__truediv__ / __floordiv__

Implements true division (/) and floor division (//) operators. Covers return types, reversed variants, and common patterns.

__truediv__(self, other)