Stop 07 · Object-Oriented ProgrammingTopics · 8/10

Dunder (Magic) Methods

Part of the Python Roadmap

In short

Why does len() work on lists, + work on strings and print() show something readable? Dunder methods. Add them to your own classes and your objects behave like Python's built-ins.

Dunder methods such as __str__, __repr__, __len__, __eq__ and __add__ let your objects work with built-in functions and operators like print(), len(), == and +.

The jaadu plugs a small handmade gadget into a wall socket and it lights up happily, just like the other appliances on the shelf.

Think of it like this

Universal plug points

Any appliance with a standard three-pin plug works in any socket in your house. Python's built-in functions and operators are those sockets. If your class has the right 'plug', like __len__ or __add__, it fits straight into len() or + without special treatment.

Watch it happen

What Python calls behind the scenes

print(x)
len(x)
x == y
x + y

1/4print(cart) calls cart.__str__() to get a friendly text version.

The big ideas

What you need to know

__str__ and __repr__

__str__ is the friendly text for users. __repr__ is the precise text for developers, shown in the REPL and debuggers.

__eq__ for comparison

Define what 'equal' means for your objects, such as same id or same amount and currency.

Operators

__add__, __sub__, __lt__ and friends let your objects use +, - and < naturally, which also makes sorted() work with __lt__.

Container behaviour

__len__, __getitem__, __contains__ and __iter__ let your class act like a list or dict.

See it in code

Walk through the code

python
1class Money:2    def __init__(self, amount: float, currency: str = "INR"):3        self.amount = amount4        self.currency = currency5 6    def __repr__(self) -> str:7        return f"Money({self.amount!r}, {self.currency!r})"8 9    def __str__(self) -> str:10        return f"{self.currency} {self.amount:,.2f}"11 12    def __eq__(self, other: object) -> bool:13        if not isinstance(other, Money):14            return NotImplemented15        return (self.amount, self.currency) == (other.amount, other.currency)16 17    def __add__(self, other: "Money") -> "Money":18        if self.currency != other.currency:19            raise ValueError("Currencies differ")20        return Money(self.amount + other.amount, self.currency)21 22    def __lt__(self, other: "Money") -> bool:23        return self.amount < other.amount24 25fees = [Money(1500), Money(250.5), Money(800)]26print(fees[0] + fees[2])        # INR 2,300.0027print(Money(100) == Money(100)) # True28print(min(fees))                # INR 250.5029print(repr(fees[1]))            # Money(250.5, 'INR')

1/6__repr__ returns an unambiguous, code-like description. !r adds quotes around strings.

A Money class that prints nicely, compares by value, adds safely and can be sorted.

Save yourself the pain

Common mistakes

Oops

Defining __eq__ and then putting objects in a set, getting TypeError: unhashable type.

Do this instead

Defining __eq__ removes the default __hash__. Add a matching __hash__, or use a frozen dataclass.

Oops

Calling obj.__len__() directly in your code.

Do this instead

Call len(obj). Dunder methods are hooks for Python to call, not for you to call by name.

Oops

Only defining __str__ and seeing <Money object at 0x...> in lists.

Do this instead

Lists show their items with repr(). Always define __repr__; __str__ falls back to it.

Your mission

A Playlist class

~25 min

Quick check

Which dunder method does print(obj) use first?

Go deeper

  1. 1Add __repr__ and __str__ to a class and print an object.
  2. 2Make two Money objects addable with __add__.
  3. 3Implement __eq__ so two objects with the same data compare as equal.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge