Python OOP
Magic (Dunder) Methods
Complete lesson for Magic (Dunder) Methods using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Python data structures and OOP where relevant.
Basics — Magic (Dunder) Methods
Section: Python OOP. Dunder methods hook your objects into Python syntax — len, +, str, indexing, context managers, and more.
What are magic methods?
- Methods named with double underscores (
__init__,__str__) are language hooks. - You rarely call them directly; Python calls them for syntax and builtins (
len(x)→x.__len__()). - Also called dunder (double underscore) methods.
| Dunder | Triggered by | Purpose |
|---|---|---|
__init__ | Class(...) | Initialise new instance |
__repr__ | repr(x), debugging | Unambiguous string |
__str__ | print(x), str(x) | Readable string |
__len__ | len(x) | Length |
__eq__ | x == y | Equality |
__add__ | x + y | Addition / concat |
__getitem__ | x[i] | Indexing |
__enter__/__exit__ | with | Context manager |
__call__ | x() | Make instance callable |
class Point:
def __init__(self, x: float, y: float) -> None:
self.x, self.y = x, y
def __repr__(self) -> str:
return f"Point({self.x!r}, {self.y!r})"
def __str__(self) -> str:
return f"({self.x}, {self.y})"
try:
p = Point(2, 3)
print(str(p))
print(repr(p))
except Exception as e:
print("Error:", e) __repr__ vs __str__
__repr__should be clear for developers; ideallyeval(repr(x))recreatesxwhen practical.__str__is for end users;printuses__str__if present, else__repr__.- Containers use
reprof elements when displaying themselves.
class User:
def __init__(self, name: str) -> None:
self.name = name
def __repr__(self) -> str:
return f"User({self.name!r})"
def __str__(self) -> str:
return self.name
try:
u = User("Asha")
print(u)
print([u])
except Exception as e:
print("Error:", e) Container protocol
__len__,__getitem__,__setitem__,__delitem__,__contains__,__iter__make objects collection-like.- Implementing
__getitem__with integer keys often enables iteration even without__iter__(sequence protocol).
class Bag:
def __init__(self, items: list[str]) -> None:
self._items = list(items)
def __len__(self) -> int:
return len(self._items)
def __getitem__(self, index: int) -> str:
return self._items[index]
def __contains__(self, item: object) -> bool:
return item in self._items
try:
b = Bag(["pen", "book", "laptop"])
print(len(b), b[1], "book" in b)
for x in b:
print(x)
except Exception as e:
print("Error:", e) Equality and hashing
__eq__defines==. If you define__eq__but not__hash__, the class becomes unhashable.- Objects used as dict keys/set members need immutable semantics and a consistent
__hash__. - Rule: equal objects must have equal hashes.
class Student:
def __init__(self, roll: int, name: str) -> None:
self.roll = roll
self.name = name
def __eq__(self, other: object) -> bool:
if not isinstance(other, Student):
return NotImplemented
return self.roll == other.roll
def __hash__(self) -> int:
return hash(self.roll)
def __repr__(self) -> str:
return f"Student({self.roll}, {self.name!r})"
try:
s1, s2 = Student(1, "Asha"), Student(1, "Asha K")
print(s1 == s2)
print({s1, s2})
except Exception as e:
print("Error:", e) Arithmetic dunders
__add__,__sub__,__mul__, … and reflected__radd__, in-place__iadd__.- Return
NotImplementedfor unsupported types.
class Vector:
def __init__(self, x: float, y: float) -> None:
self.x, self.y = x, y
def __add__(self, other: "Vector") -> "Vector":
if not isinstance(other, Vector):
return NotImplemented
return Vector(self.x + other.x, self.y + other.y)
def __repr__(self) -> str:
return f"Vector({self.x}, {self.y})"
try:
print(Vector(1, 2) + Vector(3, 4))
print(Vector(1, 2) + 5) # type: ignore[operator]
except TypeError as e:
print("Error:", e) Context managers
withcalls__enter__then__exit__(even on exceptions).__exit__(exc_type, exc, tb)may return True to suppress the exception.contextlib.contextmanagerbuilds managers from generators.
class Talk:
def __enter__(self):
print("enter")
return self
def __exit__(self, exc_type, exc, tb) -> bool:
print("exit")
if exc_type is not None:
print("Error:", exc)
return True # suppress
return False
try:
with Talk() as t:
print("inside", type(t).__name__)
raise ValueError("boom")
print("continues")
except Exception as e:
print("Error:", e) Callable objects — __call__
- Instances with
__call__behave like functions — useful for stateful callbacks.
class Adder:
def __init__(self, base: int) -> None:
self.base = base
def __call__(self, x: int) -> int:
return self.base + x
try:
add5 = Adder(5)
print(add5(10))
except Exception as e:
print("Error:", e) Advanced — Magic (Dunder) Methods
Rich comparison methods
__lt__,__le__,__gt__,__ge__,__eq__,__ne__.functools.total_orderingfills the rest if you provide__eq__and one ordering method.
from functools import total_ordering
@total_ordering
class Version:
def __init__(self, major: int, minor: int) -> None:
self.major, self.minor = major, minor
def __eq__(self, other: object) -> bool:
if not isinstance(other, Version):
return NotImplemented
return (self.major, self.minor) == (other.major, other.minor)
def __lt__(self, other: object) -> bool:
if not isinstance(other, Version):
return NotImplemented
return (self.major, self.minor) < (other.major, other.minor)
try:
print(Version(1, 2) < Version(1, 10))
print(Version(2, 0) >= Version(1, 9))
except Exception as e:
print("Error:", e) Attribute access hooks
__getattr__runs for missing attributes;__getattribute__for every access (easy to recurse — usesuper()carefully).__setattr__/__delattr__intercept writes/deletes.
class Config:
def __init__(self) -> None:
super().__setattr__("_data", {"host": "localhost"})
def __getattr__(self, name: str):
try:
return self._data[name]
except KeyError as e:
raise AttributeError(name) from e
def __setattr__(self, name: str, value) -> None:
if name.startswith("_"):
super().__setattr__(name, value)
else:
self._data[name] = value
try:
cfg = Config()
print(cfg.host)
cfg.port = 8080
print(cfg.port)
print(cfg.missing)
except AttributeError as e:
print("Error:", e) __new__ vs __init__
__new__creates and returns the instance (classmethod-like);__init__initialises it.- Immutable subclasses (
tuple,str) customise__new__. - Singletons sometimes override
__new__to return a cached instance.
Truthy objects — __bool__ / __len__
bool(x)uses__bool__if defined, else__len__!= 0, else True.
class Basket:
def __init__(self, n: int) -> None:
self.n = n
def __bool__(self) -> bool:
return self.n > 0
try:
print(bool(Basket(0)), bool(Basket(2)))
except Exception as e:
print("Error:", e) Formatting — __format__
format(x, spec)and f-strings with specs call__format__.
class Rupee:
def __init__(self, amount: float) -> None:
self.amount = amount
def __format__(self, spec: str) -> str:
if spec == "inr":
return f"₹{self.amount:,.2f}"
return format(self.amount, spec)
try:
print(f"{Rupee(1500):inr}")
except Exception as e:
print("Error:", e) Tricky Interview Points
Q1) What are magic/dunder methods?
Answer Special methods with double-underscore names that Python calls to implement operators, builtins, and syntax features.
Q2) Difference between __str__ and __repr__?
Answer __str__ is human-friendly; __repr__ is developer-friendly and ideally unambiguous. print uses __str__ when available.
Q3) How does len(obj) work?
Answer It calls obj.__len__() and validates a non-negative int result.
Q4) Why did my class become unhashable after writing __eq__?
Answer Python sets __hash__ = None when __eq__ is user-defined unless you also define a consistent __hash__.
Q5) How do you support the with statement?
Answer Implement __enter__ and __exit__. __exit__ receives exception info and may return True to suppress it.
Q6) What is __call__?
Answer Makes instances callable like functions: instance(args).
Q7) __new__ vs __init__?
Answer __new__ constructs the object; __init__ initialises it. __new__ is needed for immutables and some singleton patterns.
Q8) What should __add__ return for unsupported types?
Answer NotImplemented, so Python can try the reflected operation on the other operand.
Q9) How do you make an object iterable?
Answer Define __iter__ returning an iterator, or implement sequence-style __getitem__.
Q10) What is __getattr__ used for?
Answer Lazy/default attribute access when normal lookup fails — e.g. proxies or dynamic config keys.
Q11) Does print(x) call __repr__?
Answer It prefers __str__; if missing, it falls back to __repr__.
Q12) Name dunders for indexing and membership.
Answer __getitem__, __setitem__, __delitem__, __contains__.
Simple Programs
Money with +, ==, and repr
class Money:
def __init__(self, amount: float, currency: str = "INR") -> None:
self.amount = amount
self.currency = currency
def __add__(self, other: "Money") -> "Money":
if not isinstance(other, Money) or other.currency != self.currency:
return NotImplemented
return Money(self.amount + other.amount, self.currency)
def __eq__(self, other: object) -> bool:
if not isinstance(other, Money):
return NotImplemented
return self.amount == other.amount and self.currency == other.currency
def __repr__(self) -> str:
return f"Money({self.amount}, {self.currency!r})"
try:
print(Money(100) + Money(50))
print(Money(10) == Money(10))
print(Money(10) + Money(5, "USD"))
except TypeError as e:
print("Error:", e) Notebook as a sequence
class Notebook:
def __init__(self) -> None:
self._pages: list[str] = []
def add(self, text: str) -> None:
self._pages.append(text)
def __len__(self) -> int:
return len(self._pages)
def __getitem__(self, i: int) -> str:
return self._pages[i]
try:
nb = Notebook()
nb.add("inheritance")
nb.add("polymorphism")
print(len(nb), nb[0])
except Exception as e:
print("Error:", e) Timer context manager
import time
class Timer:
def __enter__(self):
self.t0 = time.perf_counter()
return self
def __exit__(self, exc_type, exc, tb) -> None:
self.elapsed = time.perf_counter() - self.t0
print(f"elapsed={self.elapsed:.4f}s")
if exc_type is not None:
print("Error:", exc)
try:
with Timer():
sum(range(100000))
except Exception as e:
print("Error:", e) Callable counter
class Counter:
def __init__(self) -> None:
self.n = 0
def __call__(self) -> int:
self.n += 1
return self.n
try:
c = Counter()
print(c(), c(), c())
except Exception as e:
print("Error:", e) Suppress via __exit__
class IgnoreValueError:
def __enter__(self):
return self
def __exit__(self, exc_type, exc, tb) -> bool:
if exc_type is ValueError:
print("Error:", exc)
return True
return False
try:
with IgnoreValueError():
raise ValueError("bad input")
print("still running")
except Exception as e:
print("Error:", e) Problem Solving Tricks
- Implement
__repr__first — it helps debugging everywhere. - Keep
__hash__aligned with__eq__; only hash immutables. - Use
NotImplemented, not a boolean False, for unsupported operators. @total_orderingreduces boilerplate for comparisons.- Prefer
contextlib.contextmanagerfor simple with-blocks. - Avoid heavy logic in
__getattribute__— easy to create infinite recursion. - f-strings call
__format__/__str__paths — test both. - Returning True from
__exit__swallows exceptions — use deliberately. - Sequence protocol:
__len__+__getitem__unlocks many builtins. - Document dunders in class docs; they are part of your public behaviour.
Practice Programs List
- Write Point with __repr__, __str__, __add__, and __eq__.
- Build a Deck with __len__, __getitem__, and __contains__.
- Make Student hashable by roll number; put instances in a set.
- Create a with-manager that logs enter/exit and prints exception messages.
- Implement a callable Averager that tracks running mean.
- Use total_ordering on a Score(major, minor) class.
- Proxy attributes with __getattr__ to an inner dict.
- Show what happens when __eq__ exists without __hash__ (set insert error — catch it).
- Implement __bool__ on an empty/non-empty Cart.
- Add __format__ for a Currency type with spec "inr".