OOP & classes
Classes, instances, methods, dataclasses, and object-oriented design in Python.
Add property getter setter validation in Python
Shows how to use @property with a setter to validate values before assigning them in a Python class.
class Temperature:
def __init__(self, celsius=0):
self._celsius = celsius # Use underscore to avoid recursion
@property
def celsius(self):
"""Getter returns the stored value."""
return self._celsius
@celsius.setter
def celsius(self, value):
"""Setter valid…
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 Validate Data Types in Python with a Class
A beginner-friendly Python class that checks if a value is a string, integer, float, list, or empty, using simple methods and isinstance checks.
class DataValidator:
"""A simple data validation helper for beginners."""
def __init__(self, data):
self.data = data
def is_string(self):
return isinstance(self.data, str)
def is_integer(self):
return isinstance(self.data, int) and not isinstance(self.data, bool)
…
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.