Python 101Free
CLASSES AND OOP

Dunder Methods

Special methods that hook into Python syntax.

SECTION 01

init and repr

__init__ is the constructor. Python calls it after creating a new instance to give the class a chance to populate attributes. def __init__(self, x, y): self.x = x; self.y = y is the canonical pattern.

__repr__ defines what repr(obj) returns and what the REPL shows when you evaluate an instance. The convention is to return a string that, if you typed it back at a Python prompt, would reconstruct the object: Point(3, 4).

A good __repr__ is one of the cheapest debugging tools you can write. When something goes wrong and you log a list of your objects, repr is what produces the output. Spending two minutes writing it pays off the first time you have to inspect a bug.

python
class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __repr__(self):
        return f"Point({self.x}, {self.y})"

Point(3, 4)   # Point(3, 4)
SECTION 02

Operator dunders

Python's operators are sugar for dunder method calls. a == b invokes a.__eq__(b). a + b invokes a.__add__(b). len(a) invokes a.__len__(). Implementing these on your class makes instances participate in built-in syntax.

The value of this is not raw cleverness. It is that your custom types can be used the way other Python objects are used. A Vec class that implements __add__ lets users write v1 + v2 instead of v1.add(v2). Code that consumes vectors does not need to know they are custom types.

Do not overdo this. Implement the dunders that have an obvious meaning for your type. If + does not have a natural meaning for your class, do not define __add__ just because you can.

python
class Vec:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __add__(self, other):
        return Vec(self.x + other.x, self.y + other.y)

    def __eq__(self, other):
        return (self.x, self.y) == (other.x, other.y)
← PREVIOUS
Inheritance
NEXT →
Properties and Encapsulation