Reference library

OOP & classes

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

15 matches
OOP & classes medium

Borg pattern shared state in Python

Implement the Borg pattern to share state across class instances by assigning a class-level dictionary to each instance's __dict__.

borg monostate shared-state
Python
class Borg:
    _shared_state = {}

    def __init__(self):
        self.__dict__ = Borg._shared_state


class ConfigManager(Borg):
    def __init__(self):
        super().__init__()
        if not hasattr(self, "settings"):
            self.settings = {}

    def set(self, key, value):
        self.settings[key] = va…
15 0 Open
OOP & classes medium

Bridge Pattern in Python: Separate Abstraction from Implementation

Implement the Bridge design pattern in Python so that an abstraction (remote control) can operate on different device implementations independently.

bridge design-pattern oop
Python
class RemoteControl:
    """Abstraction: controls a device without knowing implementation details."""
    def __init__(self, device):
        self.device = device

    def toggle_power(self):
        if self.device.is_enabled():
            self.device.disable()
            return "Power off"
        else:
           …
16 0 Open
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…
14 0 Open
OOP & classes medium

How to Build a Linked List Node Class in Python

Create a Node class and a LinkedList class with insert, remove, and display methods to manage a singly linked list.

linked-list node oop
Python
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

class LinkedList:
    def __init__(self):
        self.head = None

    def insert(self, data):
        new_node = Node(data)
        if not self.head:
            self.head = new_node
        else:
            current = self.…
12 0 Open
OOP & classes medium

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 data-splitting slicing
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)]
   …
14 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 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.

lazy-loading proxy properties
Python
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…
15 0 Open
OOP & classes medium

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.

pickle serialization getstate
Python
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…
13 0 Open
OOP & classes medium

How to Use __slots__ in Python Classes for Memory Efficiency

Defines classes with __slots__ to prevent dynamic attribute creation and reduce memory usage, including inheritance with additional slots.

slots oop memory
Python
```python
class Person:
    __slots__ = ("name", "age")

    def __init__(self, name: str, age: int):
        self.name = name
        self.age = age

    def greet(self) -> str:
        return f"Hi, I'm {self.name} and I'm {self.age} years old."


class Employee(Person):
    __slots__ = ("role",)

    def __init__(se…
13 0 Open
OOP & classes medium

Memento Pattern in Python: Save and Restore Object State

Implement the Memento design pattern to snapshot and restore an object's state, demonstrated with a text editor undo feature.

memento design-pattern undo
Python
class TextEditor:
    def __init__(self, text="", cursor_pos=0):
        self.text = text
        self.cursor_pos = cursor_pos

    def type_text(self, new_text):
        self.text += new_text
        self.cursor_pos += len(new_text)

    def move_cursor(self, pos):
        self.cursor_pos = max(0, min(pos, len(self.t…
14 0 Open
OOP & classes medium

Python Abstract Class with Concrete Subclasses

Define an abstract base class with abstract methods and implement them in concrete subclasses like Rectangle and Circle.

abc abstract-methods oop
Python
from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

    @abstractmethod
    def perimeter(self):
        pass

class Rectangle(Shape):
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        ret…
14 0 Open
OOP & classes medium

Template Method Pattern in Python: Define Base Class with Algorithm Steps

Create a template method base class using ABC that defines the skeleton of an algorithm while letting subclasses implement specific steps.

template-method abstract-class design-pattern
Python
from abc import ABC, abstractmethod


class DataProcessor(ABC):
    """Template method that defines the skeleton of an algorithm."""
    
    def process(self):
        """Template method - defines the sequence of steps."""
        self.load_data()
        self.clean_data()
        self.transform_data()
        self.s…
12 0 Open
OOP & classes medium

Understanding Multiple Inheritance Method Resolution Order in Python

This code demonstrates how Python's MRO determines which greet method is called in a diamond inheritance scenario, and prints the full MRO for class D.

multiple inheritance mro inheritance
Python
class A:
    def greet(self):
        return "Hello from A"

class B(A):
    def greet(self):
        return "Hello from B"

class C(A):
    def greet(self):
        return "Hello from C"

class D(B, C):
    pass


if __name__ == "__main__":
    d = D()
    print(d.greet())
    print(D.__mro__)
12 0 Open
OOP & classes medium

Unit of Work Pattern: Track Changes, Commit, and Rollback in Python

This code defines a UnitOfWork class that tracks operations (add) and supports commit to apply changes and rollback to revert them, using a dataclass-based logger.

unit-of-work dataclass transaction
Python
from dataclasses import dataclass, field
from typing import Any, Callable, List, Tuple


@dataclass
class UnitOfWork:
    log: List[Tuple[str, Callable, tuple, dict]] = field(default_factory=list)

    def track(self, operation: str, fn: Callable, *args, **kwargs):
        self.log.append((operation, fn, args, kwargs)…
13 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.