Reference library

OOP & classes

Classes, instances, methods, dataclasses, and object-oriented design in Python.

9 matches
OOP & classes medium

Composable Predicates with the &, |, ~ Operators in Python

Define a reusable Predicate class that combines boolean checks with & (AND), | (OR), and ~ (NOT) operators.

predicates operator-overloading oop
Python
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…
13 0 Open
OOP & classes easy

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.

composition design-patterns oop
Python
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, …
13 0 Open
OOP & classes medium

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.

command-pattern design-patterns oop
Python
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…
13 0 Open
OOP & classes medium

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.

state-pattern design-patterns oop
Python
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…
12 0 Open
OOP & classes medium

How to Use abstractmethod in Python

Define an abstract base class with abstract methods to enforce a common interface across subclasses.

oop abstract abc
Python
import abc

class Shape(abc.ABC):
    @abc.abstractmethod
    def area(self):
        """Calculate area of the shape."""

    @abc.abstractmethod
    def perimeter(self):
        """Calculate perimeter of the shape."""

class Rectangle(Shape):
    def __init__(self, width, height):
        self.width = width
        s…
10 0 Open
OOP & classes medium

How to implement a Facade class to simplify subsystem calls in Python

Use a Facade class to wrap complex subsystem interactions behind a simple start() method, hiding the details and providing a clean interface.

facade design-patterns oop
Python
class CPU:
    def freeze(self):
        print("CPU: freezing")

    def jump(self, position):
        print(f"CPU: jumping to {position}")

    def execute(self):
        print("CPU: executing")


class Memory:
    def load(self, position, data):
        print(f"Memory: loading '{data}' at {position}")


class HardDr…
15 0 Open
OOP & classes medium

Implement the Strategy Pattern with Interchangeable Algorithm Classes in Python

Uses abstract base classes to define a SortStrategy interface, then swaps between BubbleSort and QuickSort at runtime.

strategy-pattern oop abstract-class
Python
from abc import ABC, abstractmethod
from typing import List


class SortStrategy(ABC):
    @abstractmethod
    def sort(self, data: List[int]) -> List[int]:
        pass


class BubbleSort(SortStrategy):
    def sort(self, data: List[int]) -> List[int]:
        result = data[:]
        n = len(result)
        for i in…
12 0 Open
OOP & classes easy

Python Factory Method: Create Shapes by Type String

A factory method that maps a type string to a concrete shape class and returns an instance, with runtime error handling.

factory-pattern oop polymorphism
Python
class Shape:
    def draw(self):
        raise NotImplementedError


class Circle(Shape):
    def draw(self):
        return "Drawing a circle"


class Square(Shape):
    def draw(self):
        return "Drawing a square"


class Triangle(Shape):
    def draw(self):
        return "Drawing a triangle"


class ShapeFact…
12 0 Open
OOP & classes medium

Visitor Pattern in Python: Double Dispatch Demo

Demonstrates the Visitor design pattern with double dispatch so operations on Dog and Cat objects are selected at runtime without modifying their classes.

visitor-pattern design-patterns double-dispatch
Python
class Animal:
    def accept(self, visitor):
        visitor.visit(self)

class Dog(Animal):
    def speak(self):
        return "Woof!"

class Cat(Animal):
    def speak(self):
        return "Meow!"

class SoundVisitor:
    def visit(self, animal):
        if isinstance(animal, Dog):
            return self.visit_do…
11 0 Open

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.