OOP & classes
Classes, instances, methods, dataclasses, and object-oriented design in Python.
How to Create Static Methods in a Python Class
Shows how to define and call static methods inside a class using @staticmethod, with utility functions that don't need instance or class state.
class MathUtils:
"""Utility class demonstrating static methods."""
@staticmethod
def add(a, b):
"""Return the sum of two numbers."""
return a + b
@staticmethod
def multiply(a, b):
"""Return the product of two numbers."""
return a * b
@staticmethod
…
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 Create a Data Helper Class in Python with OOP
A complete OOP example with User, Post, and Blog classes that manage data relationships and provide clear helper methods.
class User:
def __init__(self, name, email):
self.name = name
self.email = email
self.posts = []
def create_post(self, title, content):
post = Post(title, content, self)
self.posts.append(post)
return post
def get_post_count(self):
return len(self.p…
How to Create a Data Splitter Class in Python
This code defines a DataSplitter class that splits data by index, into chunks, or by a predicate, demonstrating OOP principles in Python.
class DataSplitter:
def __init__(self, data):
self.data = list(data)
def split_by_index(self, index):
return self.data[:index], self.data[index:]
def split_into_chunks(self, chunk_size):
return [self.data[i:i + chunk_size] for i in range(0, len(self.data), chunk_size)]
…
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 Create an Iterable Class with __iter__ and __next__ in Python
Build custom iterable classes in Python by implementing the __iter__ and __next__ dunder methods to yield items on demand.
class EvenNumbers:
def __init__(self, limit):
self.limit = limit
self.current = 0
def __iter__(self):
return self
def __next__(self):
if self.current >= self.limit:
raise StopIteration
result = self.current
self.current += 2
return resul…
How to Define Dataclass Field Defaults in Python
Implement a Python dataclass with default values for simple fields and default factories for mutable collections.
from dataclasses import dataclass, field
from typing import List
@dataclass
class Product:
name: str
price: float = 0.0
quantity: int = 0
tags: List[str] = field(default_factory=list)
metadata: dict = field(default_factory=dict)
if __name__ == "__main__":
p1 = Product("Laptop", 999.99, 5)
…
How to Define a Simple Class with __init__ and __repr__ in Python
Defines a Person class with __init__ to store name and age, and __repr__ to give a readable string representation.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"Person(name='{self.name}', age={self.age})"
if __name__ == "__main__":
p1 = Person("Alice", 30)
p2 = Person("Bob", 25)
print(p1)
print(p2)
How to Define a Simple Python Class with __init__ and __repr__
Define a basic Python class with an __init__ method to set instance attributes and a __repr__ method for a readable representation of objects.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"Person(name={self.name!r}, age={self.age!r})"
if __name__ == "__main__":
person = Person("Alice", 30)
print(person)
How to Implement Iterator Protocol on a Custom Class in Python
Create a custom iterable class by defining the __iter__ and __next__ methods, enabling use in for loops and list conversions.
class Countdown:
"""Iterator that counts down from start to 0."""
def __init__(self, start):
self.start = start
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current < 0:
raise StopIteration
value = self.current
…
How to Implement Rich Comparison Ordering in Python Classes
This code demonstrates how to implement rich comparison operators (like <, <=, >, >=, ==, !=) in a Python class by defining __lt__ and __eq__, enabling sorting and ordering of custom objects.
class Task:
def __init__(self, priority, name):
self.priority = priority
self.name = name
def __lt__(self, other):
if not isinstance(other, Task):
return NotImplemented
return self.priority < other.priority
def __eq__(self, other):
if not isinstance(oth…
How to Implement a Queue Class in Python Using deque
Build a FIFO queue class in Python backed by the collections.deque container with enqueue, dequeue, peek, and size methods.
from collections import deque
class Queue:
def __init__(self):
self._items = deque()
def enqueue(self, item):
self._items.append(item)
def dequeue(self):
if self.is_empty():
raise IndexError("dequeue from empty queue")
return self._items.popleft()
…
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 Command Pattern with Undo in Python
Python code demonstrating the Command design pattern with undo and redo support using action objects and a history manager.
class Command:
def execute(self):
raise NotImplementedError
def undo(self):
raise NotImplementedError
class AddTextCommand(Command):
def __init__(self, document, text):
self.document = document
self.text = text
def execute(self):
self.document.append(self.tex…
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 Implement the State Pattern in Python
Implement the State design pattern in Python by delegating behavior to state objects, letting a media player change actions dynamically without if-else chains.
class State:
def play(self, player): pass
def pause(self, player): pass
def stop(self, player): pass
class PlayingState(State):
def play(self, player):
return "Already playing"
def pause(self, player):
player.state = PausedState()
return "Pausing playback"
def stop(self…
How to Lazy Load an Expensive Attribute with a Proxy in Python
This code shows a Proxy class that lazily loads an ExpensiveResource only when first accessed, caching it for subsequent uses.
class ExpensiveResource:
def __init__(self, name):
self.name = name
print(f"Expensive resource '{name}' created (e.g., DB connection)")
def use(self):
return f"Using {self.name}"
class Proxy:
def __init__(self, name):
self._name = name
self._resource = None
@p…
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 Use __getstate__ and __setstate__ for Pickle in Python
Customize Python object serialization with the pickle __getstate__ and __setstate__ hooks to control exactly what data is stored and how it is restored.
import pickle
class Temperature:
def __init__(self, celsius):
self.celsius = celsius
def __getstate__(self):
"""Customize what gets pickled."""
state = self.__dict__.copy()
# Convert to Fahrenheit for storage (simulate transformation)
state['fahrenheit'] = (self.celsiu…
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.