Python Dunder (Magic) Methods

Automatically called special methods in Python with real usage context

In Detail

1. Object Lifecycle Methods

Dunder Method Automatically Called When
__new__ A new object is created (before __init__)
__init__ An object is initialized after creation
__del__ An object is destroyed / garbage collected

2. String & Representation Methods

Dunder Method Automatically Called When
__str__ print(object) or str(object)
__repr__ repr(object) or debugging in console
__format__ format(object) or f-strings

3. Arithmetic & Operator Overloading

Dunder Method Automatically Called When
__add__ obj1 + obj2
__sub__ obj1 - obj2
__mul__ obj1 * obj2
__truediv__ obj1 / obj2
__floordiv__ obj1 // obj2
__mod__ obj1 % obj2

4. Comparison Methods

Dunder Method Automatically Called When
__eq__ obj1 == obj2
__ne__ obj1 != obj2
__lt__ obj1 < obj2
__le__ obj1 <= obj2
__gt__ obj1 > obj2
__ge__ obj1 >= obj2

5. Container, Indexing & Iteration

Dunder Method Automatically Called When
__len__ len(object)
__getitem__ object[index]
__setitem__ object[index] = value
__delitem__ del object[index]
__iter__ for x in object
__next__ next(iterator)
__contains__ item in object

6. Callable & Context Manager

Dunder Method Automatically Called When
__call__ object() is invoked like a function
__enter__ Entering a with block
__exit__ Exiting a with block