Examples of Dunder Methods

What are some examples of dunder methods in Python, and when are they called?

Answer

Common examples of dunder methods include:

  • __init__: called when an object is instantiated.

  • __str__: called by str() or print() to get a readable string representation.

  • __len__: called by len().

  • __getitem__: called when using indexing or slicing.

  • __iter__ and __next__: called during iteration (e.g., in a for-loop).

  • __add__: called for the + operator.

Back to collection