metodos-dunder-python

Dunder Methods in Python

  • 3 min

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:

MethodDescription
__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.