What are dunder methods and how do they implement Python's data model?medium

Type
conceptual
Topic
dunder-methods
Frequency
common
Tags
dunder, magic methods, data model, protocol, OOP
Answer

Dunder (double-underscore) methods let your objects respond to Python's built-in operators and functions. __len__ powers len(obj), __getitem__ powers obj[key], __enter__/__exit__ power the with statement — the same protocol used by lists, dicts, and every built-in type.

Explanation

When you write len(x), Python calls x.__len__(). When you write x[0], Python calls x.__getitem__(0). When you write a + b, Python calls a.__add__(b). This extensibility lets custom classes behave exactly like built-ins. Defining __eq__ removes the default __hash__ — Python makes the class unhashable (unusable in sets or as dict keys) unless you also define __hash__. __call__ makes an instance callable like a function. Returning True from __exit__ suppresses any exception raised inside the with block.

Follow-upHow would you make a custom class usable with the with statement?
Follow-upWhat happens to __hash__ when you define __eq__?
Follow-upWhat does __call__ do and when would you use it?