OOP & classes
Classes, instances, methods, dataclasses, and object-oriented design in Python.
How to Create Immutable Data Classes with frozen=True in Python
Create immutable data classes in Python using @dataclass(frozen=True) to prevent attribute modifications after instantiation.
from dataclasses import dataclass
@dataclass(frozen=True)
class Point:
x: float
y: float
def distance_from_origin(self) -> float:
return (self.x**2 + self.y**2) ** 0.5
if __name__ == "__main__":
p = Point(3.0, 4.0)
print(p)
print(f"Distance from origin: {p.distance_from_origin():.2f}…
How to Create an Immutable Money Class in Python with dataclasses
Define a frozen dataclass Money that holds an amount and currency, enforces non-negative amounts, and supports safe addition across matching currencies.
from dataclasses import dataclass
@dataclass(frozen=True)
class Money:
amount: float
currency: str = "USD"
def __post_init__(self) -> None:
if self.amount < 0:
raise ValueError("amount must be non-negative")
def add(self, other: "Money") -> "Money":
if self.currency != o…
How to Use NamedTuples for Lightweight Records in Python
Create lightweight, immutable data records with namedtuple that behave like tuples but have named fields for improved readability and access.
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p)
print(p.x, p.y)
print(p[0], p[1])
x, y = p
print(x, y)
print(p._asdict())
p2 = p._replace(x=10)
print(p2)
if __name__ == "__main__":
print("NamedTuple demo complete")
Browse by section
Each section groups closely related Python snippets.
OOP & classes — Python code examples
What you will find here
This page collects oop & classes snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.