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)
1 more section

Create a free account to access all sections and animations.

Create free accountAlready have an account? Sign in