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…
Binary Tree Inorder Traversal in Python
Define a TreeNode class and recursively print in-order traversal (left, node, right) of a binary tree.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def inorder_traversal(root):
return inorder_traversal(root.left) + [root.val] + inorder_traversal(root.right) if root else []
if __name__ == "__main__":
# Build a…
Borg pattern shared state in Python
Implement the Borg pattern to share state across class instances by assigning a class-level dictionary to each instance's __dict__.
class Borg:
_shared_state = {}
def __init__(self):
self.__dict__ = Borg._shared_state
class ConfigManager(Borg):
def __init__(self):
super().__init__()
if not hasattr(self, "settings"):
self.settings = {}
def set(self, key, value):
self.settings[key] = va…
Bridge Pattern in Python: Separate Abstraction from Implementation
Implement the Bridge design pattern in Python so that an abstraction (remote control) can operate on different device implementations independently.
class RemoteControl:
"""Abstraction: controls a device without knowing implementation details."""
def __init__(self, device):
self.device = device
def toggle_power(self):
if self.device.is_enabled():
self.device.disable()
return "Power off"
else:
…
Composable Predicates with the &, |, ~ Operators in Python
Define a reusable Predicate class that combines boolean checks with & (AND), | (OR), and ~ (NOT) operators.
class Predicate:
def __init__(self, func, name=None):
self.func = func
self.name = name or getattr(func, "__name__", "predicate")
def __call__(self, value):
return self.func(value)
def __and__(self, other):
return Predicate(lambda v: self(v) and other(v), f"({self.name} AN…
Composition over Inheritance: How to Build a Wallet Account in Python
Demonstrates composition by wrapping a WalletAccount class in an AuditedWallet decorator-like class to add behavior without changing the original class.
class WalletAccount:
def __init__(self, owner, balance=0.0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("Deposit must be positive")
self.balance += amount
return self.balance
def withdraw(self, …
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…
Define an Enum for Status Codes in Python
Create a readable StatusCode enum with HTTP-style status values and iterate over its members using the standard library Enum class.
from enum import Enum
class StatusCode(Enum):
OK = 200
CREATED = 201
BAD_REQUEST = 400
UNAUTHORIZED = 401
NOT_FOUND = 404
INTERNAL_ERROR = 500
if __name__ == "__main__":
code = StatusCode.NOT_FOUND
print(f"Name: {code.name}")
print(f"Value: {code.value}")
print(f"Is it OK? {co…
Design a Data Helper Class in Python
Create a simple Object-Oriented data helper with DataPoint and Dataset classes that store, describe, and summarize coordinate points.
class DataPoint:
def __init__(self, x, y):
self.x = x
self.y = y
self.label = None
def describe(self):
"""Return a human-readable description of the data point."""
base = f"DataPoint(x={self.x}, y={self.y})"
return f"{base}, label='{self.label}'" if self.label e…
Filtering data with a Python class helper
A beginner-friendly DataFilter class that filters lists of dictionaries by exact match, greater-than, and substring conditions.
class DataFilter:
"""A beginner-friendly helper to filter lists of dictionaries."""
def __init__(self, data):
self.data = data
def filter_by(self, key, value):
"""Return items where data[key] == value."""
return [item for item in self.data if item.get(key) == value]
…
Graph Class with Adjacency Dict in Python
Build an undirected graph class using a dictionary of adjacency lists with methods to add vertices, edges, remove edges, and query neighbors.
class Graph:
def __init__(self):
self.adjacency = {}
def add_vertex(self, vertex):
if vertex not in self.adjacency:
self.adjacency[vertex] = []
def add_edge(self, u, v):
self.add_vertex(u)
self.add_vertex(v)
self.adjacency[u].append(v)
self.adja…
Group Data Helper Class in Python
A simple Python class that stores items under named groups, retrieves groups, items, and counts, and formats them as a readable summary.
class GroupData:
"""A simple helper class to store and group data for beginners."""
def __init__(self):
self.items = []
def add(self, item, group):
"""Add an item under a given group name."""
self.items.append({"item": item, "group": group})
def get_groups(self):
"""R…
How to Build a Class Method Alternative Constructor from Dict in Python
Use a classmethod alternative constructor to build a Book instance from a dictionary with sensible defaults.
class Book:
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages
@classmethod
def from_dict(cls, data):
"""Alternative constructor that builds a Book from a dictionary."""
return cls(
title=data["title"],
…
How to Build a Context Manager Class in Python
Create a reusable context manager class that opens and automatically closes resources using the with statement.
class FileResource:
def __init__(self, filename, mode='r'):
self.filename = filename
self.mode = mode
self.file = None
def __enter__(self):
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_value, traceback):
if se…
How to Build a Data Helper Class in Python with OOP
Create a beginner-friendly Python class that loads CSV data, filters records by field, and counts entries using object-oriented programming.
class DataHelper:
"""A beginner-friendly OOP helper for handling simple datasets."""
def __init__(self, filename):
self.filename = filename
self.data = self._load_data()
def _load_data(self):
"""Load data from a CSV file into a list of dictionaries."""
import csv
…
How to Build a Fluent Interface with the Builder Pattern in Python
Learn to implement a fluent builder pattern in Python by chaining methods that return self, enabling readable object construction.
class Pizza:
def __init__(self):
self.size = None
self.toppings = []
self.crust = None
def set_size(self, size):
self.size = size
return self
def add_topping(self, topping):
self.toppings.append(topping)
return self
def set_crust(self, crust):
…
How to Build a Linked List Node Class in Python
Create a Node class and a LinkedList class with insert, remove, and display methods to manage a singly linked list.
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insert(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
else:
current = self.…
How to Build an In-Memory CRUD Repository Class in Python
Define a Python Repository class that stores objects in a dictionary and supports create, read, update, delete, and list operations.
class Repository:
def __init__(self):
self._data = {}
def create(self, key, value):
self._data[key] = value
return key
def read(self, key):
return self._data.get(key)
def update(self, key, value):
if key not in self._data:
raise KeyError(f"Key '{ke…
How to Call a Parent Class __init__ with super() in Python
Shows how to chain __init__ calls through a class hierarchy using super(), so each class sets its own attributes while reusing the parent's initialization logic.
class Animal:
def __init__(self, name, species):
self.name = name
self.species = species
print(f"Animal init: {self.name}, {self.species}")
class Mammal(Animal):
def __init__(self, name, species, fur_color):
super().__init__(name, species)
self.fur_color = fur_color
…
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 Convert Data Types in Python with a Helper Class
This code defines a beginner-friendly OOP helper class for common data conversions like string to list, list to dict, JSON string, and CSV row, with an advanced subclass for numeric casting.
class DataConverter:
"""A beginner-friendly helper class for common data conversions."""
def __init__(self, data):
self.data = data
def to_list(self):
"""Convert string data (comma-separated) to a list."""
if isinstance(self.data, str):
return [item.strip() for…
How to Copy Class Instances in Python: Shallow vs Deep Copy
Use copy.copy and copy.deepcopy to clone class instances, showing how nested objects are shared or duplicated.
import copy
class Config:
def __init__(self):
self.settings = {"theme": "dark", "language": "en"}
if __name__ == "__main__":
original = Config()
shallow_copy = copy.copy(original)
deep_copy = copy.deepcopy(original)
shallow_copy.settings["theme"] = "light"
deep_copy.settings["them…
How to Count Items in a Python Class
A beginner-friendly Inventory class that stores item quantities in a dictionary and provides add, remove, count, and summary methods.
class Inventory:
def __init__(self):
self.items = {}
def add(self, item, quantity=1):
self.items[item] = self.items.get(item, 0) + quantity
def remove(self, item, quantity=1):
if item not in self.items:
raise ValueError(f"{item} not in inventory")
self.items[it…
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}…
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.