By WebNest Studio Engineering Team
Python Tutorial
Magic Methods and Operator Overloading
Magic methods — also called dunder methods because of their double underscores — let your classes integrate with Python's syntax and built-ins. Define __str__ and print() shows something useful; define __add__ and + works on your objects; define __len__, __getitem__ and __iter__ and your class behaves like a built-in container.
This lesson covers string representations, comparison and hashing, arithmetic operator overloading, container and iteration methods, making objects callable, and the context-manager methods.
Why it matters
Special methods are how your own classes take part in the language: being printed, compared, added, sorted, looped over and used in a with statement. Libraries such as NumPy, pandas and pathlib feel natural to use precisely because they define these methods, and a class without __repr__ is painful to debug.
String Representations
__repr__ returns an unambiguous, developer-facing representation (ideally valid code to recreate the object) used by the REPL, debuggers and containers. __str__ returns a friendly representation for print() and str(); it falls back to __repr__. __format__ supports format specs in f-strings.
Comparison and Hashing
__eq__, __lt__, __le__, __gt__, __ge__ and __ne__ define comparisons; functools.total_ordering fills in the rest from __eq__ and one ordering method. If you define __eq__, define __hash__ consistently (equal objects must have equal hashes) — or leave objects unhashable if they are mutable.
Arithmetic Operators
__add__ (+), __sub__ (-), __mul__ (*), __truediv__ (/), __floordiv__, __mod__, __pow__, __neg__, __abs__. Reflected versions (__radd__, __rmul__) handle cases like 3 * vector, and in-place versions (__iadd__) handle +=. Return NotImplemented for unsupported types so Python can try the other operand.
Containers, Iteration, Calling and Context Managers
__len__, __getitem__, __setitem__, __delitem__, __contains__ and __iter__ make a class behave like a collection. __bool__ controls truthiness. __call__ makes instances callable like functions. __enter__ and __exit__ make objects usable in with statements.
Examples
__repr__, __str__ and __format__
class Money:
def __init__(self, amount, currency="INR"):
self.amount, self.currency = amount, currency
def __repr__(self):
return f"Money({self.amount!r}, {self.currency!r})"
def __str__(self):
return f"{self.currency} {self.amount:,.2f}"
def __format__(self, spec):
return f"{self.amount:{spec}} {self.currency}" if spec else str(self)
m = Money(1234.5)
print(m)
print(repr(m))
print([m])
print(f"{m:.0f}")
INR 1,234.50
Money(1234.5, 'INR')
[Money(1234.5, 'INR')]
1234 INR
Operator overloading for a Vector class
class Vector:
def __init__(self, x, y):
self.x, self.y = x, y
def __repr__(self):
return f"Vector({self.x}, {self.y})"
def __add__(self, other):
if not isinstance(other, Vector):
return NotImplemented
return Vector(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return Vector(self.x - other.x, self.y - other.y)
def __mul__(self, k):
return Vector(self.x * k, self.y * k)
__rmul__ = __mul__ # supports 3 * v
def __neg__(self):
return Vector(-self.x, -self.y)
def __abs__(self):
return (self.x ** 2 + self.y ** 2) ** 0.5
def __eq__(self, other):
return isinstance(other, Vector) and (self.x, self.y) == (other.x, other.y)
def __hash__(self):
return hash((self.x, self.y))
def __bool__(self):
return bool(self.x or self.y)
a, b = Vector(3, 4), Vector(1, 2)
print(a + b, a - b, a * 2, 3 * b, -a, abs(a))
print(a == Vector(3, 4), bool(Vector(0, 0)), len({a, Vector(3, 4)}))
try:
a + 5
except TypeError as e:
print("TypeError:", e)
Vector(4, 6) Vector(2, 2) Vector(6, 8) Vector(3, 6) Vector(-3, -4) 5.0
True False 1
TypeError: unsupported operand type(s) for +: 'Vector' and 'int'
Comparisons with total_ordering, and sorting objects
from functools import total_ordering
@total_ordering
class Version:
def __init__(self, text):
self.parts = tuple(int(p) for p in text.split("."))
def __eq__(self, other):
return self.parts == other.parts
def __lt__(self, other):
return self.parts < other.parts
def __repr__(self):
return ".".join(map(str, self.parts))
versions = [Version("3.12.1"), Version("3.9.0"), Version("3.12.0"), Version("3.10.4")]
print(sorted(versions))
print(Version("3.10.0") > Version("3.9.9"), Version("1.0") >= Version("1.0"), max(versions))
[3.9.0, 3.10.4, 3.12.0, 3.12.1]
True True 3.12.1
A container class, a callable object and a context manager
class Inventory:
def __init__(self):
self._items = {}
def __setitem__(self, name, qty):
self._items[name] = qty
def __getitem__(self, name):
return self._items.get(name, 0)
def __delitem__(self, name):
del self._items[name]
def __contains__(self, name):
return name in self._items
def __len__(self):
return len(self._items)
def __iter__(self):
return iter(sorted(self._items))
inv = Inventory()
inv["pens"] = 40; inv["books"] = 5; inv["bags"] = 2
del inv["bags"]
print(len(inv), inv["pens"], inv["lamps"], "books" in inv, list(inv))
class Discount:
def __init__(self, percent):
self.percent = percent
def __call__(self, price):
return price * (100 - self.percent) / 100
festive = Discount(20)
print(festive(500), callable(festive))
class Timer:
def __enter__(self):
print("start")
return self
def __exit__(self, exc_type, exc, tb):
print("stop, error:", exc_type.__name__ if exc_type else None)
return False
with Timer():
print("working")
2 40 0 True ['books', 'pens']
400.0 True
start
working
stop, error: None
Common Mistakes
- Defining __eq__ but not __hash__ for immutable value objects (Python makes them unhashable).
- Raising TypeError instead of returning NotImplemented from arithmetic methods.
- Making __repr__ vague ("<Vector>") so debugging output is useless.
- Overloading operators with surprising meanings (e.g. + that deletes data).
Exercise
Write a Vector class with x and y. Adding two vectors should produce a new vector, two vectors with the same values should be equal, and a vector should print in the form shown.
Expected output: Vector(4, 6) then True
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
# TODO: __repr__ -> "Vector(4, 6)"
# TODO: __add__ -> a new Vector
# TODO: __eq__ -> True when x and y match
print(Vector(1, 2) + Vector(3, 4))
print(Vector(1, 2) == Vector(1, 2))
Show hints
__add__(self, other)should returnVector(self.x + other.x, self.y + other.y).printuses__repr__when the class has no__str__.
Show solution
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"Vector({self.x}, {self.y})"
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __eq__(self, other):
return self.x == other.x and self.y == other.y
print(Vector(1, 2) + Vector(3, 4))
print(Vector(1, 2) == Vector(1, 2))
Quick quiz
1. A class defines __repr__ but not __str__. What does print(obj) show?
- A. The default text with a memory address
- B. The result of __repr__
- C. An error
- D. Nothing
Show answer
B. str() falls back to __repr__ when __str__ is not defined.
2. Which method makes len(obj) work?
- A. __size__
- B. __len__
- C. __length__
- D. __count__
Show answer
B. Built-in functions call the matching special method on the object.
3. A class defines __eq__ and nothing else. Can its objects be put in a set?
- A. Yes
- B. Only if they are equal
- C. No; defining __eq__ without __hash__ makes the objects unhashable
- D. Only in a frozenset
Show answer
C. Python sets __hash__ to None in that case. Define __hash__ consistently with __eq__ to allow it.
Interview questions
What is the difference between __str__ and __repr__?
Show answer
__repr__ is meant for developers: it should be unambiguous and ideally look like the code that would recreate the object. It is used by the REPL, by debuggers and when an object appears inside a list. __str__ is meant for end users and is used by print() and str(). If only one is written it should be __repr__, since __str__ falls back to it.
How are __eq__ and __hash__ related?
Show answer
Objects that compare as equal must have the same hash, because dictionaries and sets use the hash to find a candidate and then == to confirm it. A class that defines __eq__ therefore loses its default __hash__ and becomes unhashable unless __hash__ is also defined, typically as the hash of a tuple of the fields used in __eq__. Those fields should not change while the object is in a set or used as a key.
Key Points to Remember
- __repr__ for developers, __str__ for users, __format__ for format specs.
- Comparison methods plus @total_ordering make objects sortable; keep __hash__ consistent with __eq__.
- Arithmetic dunders (plus __r*__ and __i*__ variants) enable operator overloading.
- __len__, __getitem__, __contains__, __iter__ make container-like classes.
- __call__ makes callable objects; __enter__/__exit__ make context managers.
Practice in the playground
Write and run your own code for this topic, or start from the exercise or an example. Runs Python in your browser. Your code for each topic is kept in this browser.
Run the examples
Change an input, predict the result, then compare it with the output. Explain why the result changes.
Written by
WebNest Studio Engineering Team
Practical lessons from developers working with Java, Python, React, databases and production systems.
Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering