Learning navigation

Code with Animation

Magic (Dunder) Methods & Protocols

Master Python special double-underscore methods: __str__ versus __repr__, __len__, comparison dunders like __eq__, and operator overloading protocols.

Python7 min readConcept 15 of 24

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.

Select Built-in Operation:
# 1. Custom Vector class:
class Vector:
def __init__(self, x, y):
self.x, self.y = x, y
def __str__(self):
return f"(3, 4)"
# 2. User call:
res = str(v) # or print(v)
# "(3, 4)"
OPERATOR TO DUNDER METHOD TRANSLATORBUILT-IN SYNTAXExecuted Expression:str(v)Native Python expression→DUNDER PROTOCOLInvoked Hook:v.__str__()Special method protocolEVALUATED RUNTIME RESULT:→ "(3, 4)" (Clean user string)PROTOCOL: __str__ provides friendly formatting for print() and user UIs.If __str__ is missing, Python automatically falls back to __repr__.
★ Python Rule: Python syntax operators are powered by dunder protocols. Implementing __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.

  1. 1What does Python display when you execute `print([item])` if the class of `item` defines `__str__` but does not define `__repr__`?
  2. 2Which magic method must be implemented to allow instances of a class to be used with the `len()` built-in function?
  3. 3What does Python's `==` comparison operator evaluate by default on custom classes if `__eq__` is not defined?

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.