OOP & classes
Classes, instances, methods, dataclasses, and object-oriented design in Python.
How to Implement a Singleton Class in Python
This code demonstrates a classic Singleton pattern in Python by overriding __new__ to ensure only one instance of the class is created, even when instantiated multiple times.
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
def __init__(self):
self.value = 0
if __name__ == "__main__":
s1 = Singleton()
s2 = Singleton()
s1.value = 42
print…
How to Implement a Stack Class in Python
A complete Stack class implemented with a Python list, featuring push, pop, peek, is_empty, size, and a readable string representation.
class Stack:
def __init__(self):
self._items = []
def push(self, item):
"""Add an item to the top of the stack."""
self._items.append(item)
def pop(self):
"""Remove and return the top item. Raises IndexError if empty."""
if self.is_empty():
raise IndexE…
How to Implement the Decorator Pattern in Python to Add Behavior
This Python code demonstrates the decorator pattern by wrapping a function to add logging behavior without modifying the original function.
import functools
def logger(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__} with {args} {kwargs}")
result = func(*args, **kwargs)
print(f"{func.__name__} returned {result}")
return result
return wrapper
@logger
def add(a, b):
…
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 Use IntEnum Arithmetic for Priority Levels in Python
Demonstrates Python IntEnum arithmetic for priority levels, showing how enum members behave like integers in calculations and comparisons.
from enum import IntEnum
class Priority(IntEnum):
LOW = 1
MEDIUM = 5
HIGH = 10
CRITICAL = 20
if __name__ == "__main__":
current = Priority.MEDIUM
boosted = current + 3
lowered = current - 2
doubled = current * 2
print(f"Current: {current} ({current.value})")
print(f"Boosted (…
How to Use NamedTuples for Lightweight Records in Python
Create lightweight, immutable data records with namedtuple that behave like tuples but have named fields for improved readability and access.
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p)
print(p.x, p.y)
print(p[0], p[1])
x, y = p
print(x, y)
print(p._asdict())
p2 = p._replace(x=10)
print(p2)
if __name__ == "__main__":
print("NamedTuple demo complete")
How to Use StrEnum with auto() in Python
Define string-valued enum members automatically by using StrEnum with the auto() helper, making each member's value its own uppercase name.
from enum import StrEnum, auto
class Color(StrEnum):
RED = auto()
GREEN = auto()
BLUE = auto()
class Language(StrEnum):
PYTHON = auto()
JAVASCRIPT = auto()
RUST = auto()
print(list(Color))
print(list(Language))
print(Color.RED == "RED")
print(Language.PYTHON == "PYTHON")
print(f"Color: {Co…
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
…
How to define a custom exception class in Python with an error code attribute
Create a custom exception class with extra attributes like an error code, then raise and catch it in a try/except block.
class UserNotFoundError(Exception):
def __init__(self, user_id, error_code=404):
self.user_id = user_id
self.error_code = error_code
super().__init__(f"User with ID {user_id} was not found (error code: {error_code})")
def find_user(user_id, users_db):
if user_id not in users_db:
…
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 …
Slots Class: How to Reduce Memory Usage in Python
Use __slots__ to prevent dynamic attribute creation and reduce per-instance memory overhead, while keeping methods intact.
class SlotsDemo:
__slots__ = ("name", "age", "email")
def __init__(self, name, age, email):
self.name = name
self.age = age
self.email = email
def describe(self):
return f"{self.name}, {self.age}, {self.email}"
if __name__ == "__main__":
instance = SlotsDemo("Alice", …
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.