OOP & the Data Model
Everything in Python is an object
Section titled “Everything in Python is an object”Python is a fully object-oriented language: integers, strings, functions, modules — every value is an object with an identity, a type, and a value.
A class is the blueprint; an object (or instance) is what you create from that blueprint with ClassName(...).
x = 42print(type(x)) # <class 'int'>print(id(x)) # unique memory addressThe special-method protocol
Section titled “The special-method protocol”Python exposes nearly every built-in operation through dunder methods (double-underscore methods like __init__, __repr__, __add__).
When you write a + b, Python calls a.__add__(b).
When you write len(obj), Python calls obj.__len__().
When you write repr(obj), Python calls obj.__repr__().
This protocol is called the Python Data Model — it lets your own classes integrate seamlessly with built-in syntax and standard-library functions.
A minimal class
Section titled “A minimal class”class Point: def __init__(self, x: float, y: float) -> None: self.x = x self.y = y
def __repr__(self) -> str: return f"Point({self.x}, {self.y})"__init__is the initialiser — it runs right after the object is created and sets up instance attributes.__repr__gives the object a developer-friendly string representation.
What this module covers
Section titled “What this module covers”| Lesson | Topic |
|---|---|
| 1. Classes | class, __init__, instance vs class attributes, inheritance |
| 2. Dunder methods | __repr__, __eq__, __len__, __getitem__, __add__ |
| 3. Properties | @property, computed attributes, @classmethod, @staticmethod |
| 4. Dataclasses | @dataclass, defaults, field, frozen=True |
Runnable demo
Section titled “Runnable demo”class Point: def __init__(self, x: float, y: float) -> None: self.x = x self.y = y
def __repr__(self) -> str: return f"Point({self.x}, {self.y})"
def __add__(self, other: "Point") -> "Point": return Point(self.x + other.x, self.y + other.y)
p1 = Point(1, 2)p2 = Point(3, 4)print(p1)print(p1 + p2)print(type(p1))print(isinstance(p1, Point))Loading Python runtime (first run only)…