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 calllen()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 chat
Implement
__eq__so two members with the same data compare equal. - In an email or ticket
Add a
__repr__for easier debugging.
Keep exploring
More in Programming Fundamentals