QamoosTech
Programming FundamentalsObject-oriented programmingIntermediatePython

Dunder Method

PronunciationDUN-der METH-ud

Definition

A dunder (double-underscore) method is a special method whose name is wrapped in double underscores, such as __init__ or __len__. Python calls it for you in certain situations.

Where you hear it

In Python classes, explanations of how len(obj) or a + b work, and code reviews of custom classes.

Examples

  • Define __repr__ so the object prints clearly in logs.
  • Adding __len__ lets you call len() on the collection.
  • Defining __eq__ makes two Money objects compare equal when their amounts match.

Common mistake

Calling dunder methods directly, like obj.__len__(). Use the built-in len(obj) and let Python call them.

Don't confuse with

A private method named with one underscore, which is only a convention for internal use.

Say it at work

  • In a meeting or chatImplement __eq__ so two members with the same data compare equal.
  • In an email or ticketAdd a __repr__ for easier debugging.