Magic (Dunder) Methods & Protocols
Master Python special double-underscore methods: __str__ versus __repr__, __len__, comparison dunders like __eq__, and operator overloading protocols.
Hooking into Python Core Syntax Protocols
In Python, magic methods (also known as dunder methods because they begin and end with double underscores, like __init__) are special hooks that allow custom classes to integrate seamlessly with Python's built-in operators and functions.
Whenever you call len(my_obj), Python does not read a private property directly; it translates your call into my_obj.__len__().
Similarly, evaluating a + b invokes a.__add__(b), and checking a == b invokes a.__eq__(b). By implementing these standard methods, your custom objects behave like native Python types.
__str__ vs __repr__: The String Representations
Python provides two distinct ways to convert an object into a string:
1. __str__ is intended to be readable and user-friendly. It is called by str(obj) and print(obj) to present a clean summary for end-users.
2. __repr__ is intended to be unambiguous and developer-focused. It is called by repr(obj), interactive REPLs, and when objects are printed inside collections like lists or dictionaries.
An ideal __repr__ returns a valid Python expression string that could recreate the exact object (for example, Point(x=10, y=20)).
The Container and Comparison Protocols
Container protocols: implementing __len__(self) allows your object to answer len(obj). Implementing __getitem__(self, key) enables square-bracket indexing obj[key], and __contains__(self, item) powers the item in obj membership check.
Comparison protocols: by default, custom class instances compare equality by their memory address (identity). Implementing __eq__(self, other) enables custom value-based equality checking with ==.
Implementing __lt__(self, other) enables the < operator, which allows instances of your class to be sorted naturally using Python's built-in sorted(my_objects).
The Operator-to-Dunder Translation Lab
Test built-in Python expressions like str(), repr(), len(), and equality == against a custom Vector class. Watch how Python translates every built-in operation into a corresponding dunder method call.
__repr__ ensures clear stack traces and collection printing. Implementing __eq__ and __len__ makes objects behave like native data structures.Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- Dunder methods allow custom classes to hook into Python syntax and built-in operators.
- __repr__ is for developers and debugging; __str__ is for clean user-facing string representations.
- Always define __repr__ first; Python falls back to __repr__ if __str__ is missing.
- __len__ enables len(), __getitem__ enables indexing [key], and __eq__ enables == comparison.
- Use @dataclass to eliminate repetitive manual dunder method boilerplate.
Done with this concept?
Mark it complete to track your progress. No login needed.