OOP & classes
Classes, instances, methods, dataclasses, and object-oriented design in Python.
Compute Derived Fields with @dataclass __post_init__ in Python
Compute derived fields like distance, area, and perimeter automatically in Python dataclasses using __post_init__ and field(init=False).
from dataclasses import dataclass, field
from math import sqrt
@dataclass
class Point:
x: float
y: float
distance: float = field(init=False)
def __post_init__(self):
self.distance = sqrt(self.x ** 2 + self.y ** 2)
@dataclass
class Rectangle:
width: float
height: float
area: flo…
How to Compare Dataclass Instances by Specific Fields in Python
Use @dataclass(order=True) with field(compare=False) to control which fields determine ordering and equality between instances.
from dataclasses import dataclass, field
from typing import Any
@dataclass(order=True)
class Person:
name: str = field(compare=False)
age: int
height_cm: float
priority: int = field(compare=False, default=0)
def __repr__(self):
return f"Person(name={self.name!r}, age={self.age}, height={s…
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 Define Dataclass Field Defaults in Python
Implement a Python dataclass with default values for simple fields and default factories for mutable collections.
from dataclasses import dataclass, field
from typing import List
@dataclass
class Product:
name: str
price: float = 0.0
quantity: int = 0
tags: List[str] = field(default_factory=list)
metadata: dict = field(default_factory=dict)
if __name__ == "__main__":
p1 = Product("Laptop", 999.99, 5)
…
How to Validate User Input with a Dataclass in Python
A dataclass stores name, age, and email, and a validator class checks each field, returning a dictionary of boolean results.
from dataclasses import dataclass
@dataclass
class UserInput:
name: str
age: int
email: str
def is_valid_name(self) -> bool:
return bool(self.name.strip()) and len(self.name.strip()) >= 2
def is_valid_age(self) -> bool:
return isinstance(self.age, int) and 0 < self.age < 150
…
Validate dataclass fields with __post_init__ in Python
Add custom validation to a Python dataclass inside __post_init__, raising ValueError or TypeError for invalid field values.
from dataclasses import dataclass, field
from typing import Optional
@dataclass
class Product:
name: str
price: float
quantity: int = 1
category: Optional[str] = None
def __post_init__(self):
if not self.name or not isinstance(self.name, str):
raise ValueError("name must be a…
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.