Reference library

OOP & classes

Classes, instances, methods, dataclasses, and object-oriented design in Python.

2 matches
OOP & classes easy

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).

dataclasses oop derived-fields
Python
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…
12 0 Open
OOP & classes easy

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.

dataclasses validation post-init
Python
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…
11 0 Open

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.