Skip to main content

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.

L1

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.
DunderTriggered byPurpose
__init__Class(...)Initialise new instance
__repr__repr(x), debuggingUnambiguous string
__str__print(x), str(x)Readable string
__len__len(x)Length
__eq__x == yEquality
__add__x + yAddition / concat
__getitem__x[i]Indexing
__enter__/__exit__withContext 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; ideally eval(repr(x)) recreates x when practical.
  • __str__ is for end users; print uses __str__ if present, else __repr__.
  • Containers use repr of 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 NotImplemented for 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

  • with calls __enter__ then __exit__ (even on exceptions).
  • __exit__(exc_type, exc, tb) may return True to suppress the exception.
  • contextlib.contextmanager builds 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)
L2

Advanced — Magic (Dunder) Methods

Rich comparison methods

  • __lt__, __le__, __gt__, __ge__, __eq__, __ne__.
  • functools.total_ordering fills 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 — use super() 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)
L3

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__.

L4

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)
L5

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_ordering reduces boilerplate for comparisons.
  • Prefer contextlib.contextmanager for 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.
L6

Practice Programs List

  1. Write Point with __repr__, __str__, __add__, and __eq__.
  2. Build a Deck with __len__, __getitem__, and __contains__.
  3. Make Student hashable by roll number; put instances in a set.
  4. Create a with-manager that logs enter/exit and prints exception messages.
  5. Implement a callable Averager that tracks running mean.
  6. Use total_ordering on a Score(major, minor) class.
  7. Proxy attributes with __getattr__ to an inner dict.
  8. Show what happens when __eq__ exists without __hash__ (set insert error — catch it).
  9. Implement __bool__ on an empty/non-empty Cart.
  10. Add __format__ for a Currency type with spec "inr".