In Python, Dunder methods (short for “double underscore”) are those whose name begins and ends with two underscores (__).
These methods are not called directly, but are automatically invoked by the Python interpreter in various situations (such as arithmetic operations, sequence manipulation, and context management).
Also known as magic or special methods
Some of the most common dunder methods are:
| Method | Description |
|---|---|
__init__ | Initializes a new instance of a class |
__str__ | Returns a string representation of an object, user-friendly |
__repr__ | Returns a string representation of an object, developer-friendly |
__len__ | Returns the length of an object |
__getitem__ | Allows accessing elements via indices |
__setitem__ | Allows assigning values to elements via indices |
__delitem__ | Allows deleting elements via indices |
__iter__ | Returns an iterator for the object |
__next__ | Returns the next element from the iterator |
Implementation of Dunder Methods
Let’s see how some of these methods are implemented and used in a Python class.
