OOP & classes
Classes, instances, methods, dataclasses, and object-oriented design in Python.
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…
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 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 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 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 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…
Python Adapter Class: Wrap Legacy Interface
Convert a legacy system's interface into a modern one using the Adapter pattern in Python, translating method calls and data formats.
class LegacySystem:
"""Legacy interface - old method names and parameter format."""
def query_employee_info(self, emp_id, emp_name):
return f"Legacy: {emp_id} - {emp_name}"
def update_employee_department(self, emp_id, department_code):
return f"Legacy: Updated {emp_id} to dept {department_…
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.