OOP & classes
Classes, instances, methods, dataclasses, and object-oriented design in Python.
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…
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 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 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 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 a Data Formatter Class in Python
A beginner-friendly helper class to format lists, dictionaries, and stored records into readable strings.
class DataFormatter:
"""Helper class for beginners to format common data types."""
def __init__(self, name="data"):
self.name = name
self.records = []
def add_record(self, key, value):
"""Add a key-value record to the formatter."""
self.records.append({"key": key, …
How to Make a Python Class Hashable with __eq__ and __hash__
Define __eq__ and __hash__ together on a Python class so equal instances share the same hash and work correctly in sets and dictionary keys.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
if not isinstance(other, Point):
return NotImplemented
return self.x == other.x and self.y == other.y
def __hash__(self):
return hash((self.x, self.y))
def __repr…
How to Sort Data in Python with a Class Helper
This beginner-friendly class wraps the built-in sorted() function to sort numbers, strings ignoring case, and dictionaries by a specified key.
class DataSorter:
def __init__(self, data):
self.data = data
def sort_numbers(self, reverse=False):
return sorted(self.data, reverse=reverse)
def sort_strings_ignore_case(self, reverse=False):
return sorted(self.data, key=str.lower, reverse=reverse)
def sort_dicts_by_key(self…
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
…
How to merge dictionaries by a key in Python with a class
This code defines a DataMerger class that collects dictionary records and merges them by a specified key, combining fields from multiple records with the same key.
class DataMerger:
def __init__(self):
self.records = []
def add_record(self, record):
if isinstance(record, dict):
self.records.append(record)
else:
raise TypeError("Record must be a dictionary")
def merge_by_key(self, key):
merged = {}
for …
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.