Reference library

OOP & classes

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

69 matches
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

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 easy

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 validation type checking
Python
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)
…
13 0 Open
OOP & classes easy

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.

dataclass validation oop
Python
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

  …
15 0 Open
OOP & classes easy

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.

exceptions classes error-handling
Python
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:
      …
15 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 easy

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.

classes dictionaries merging
Python
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 …
13 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 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

Observer Pattern in Python: Notify Listeners

Implement the Observer design pattern in Python with a Subject class that manages listeners and notifies them with messages.

design-pattern observer oop
Python
class Subject:
    def __init__(self):
        self._observers = []

    def attach(self, observer):
        self._observers.append(observer)

    def detach(self, observer):
        self._observers.remove(observer)

    def notify(self, message):
        for observer in self._observers:
            observer.update(me…
12 0 Open
OOP & classes easy

Parse CSV Data with a Python Class

Encapsulate CSV file loading and column/row access methods in a reusable DataParser class for beginners.

oop csv parsing
Python
class DataParser:
    def __init__(self, file_path):
        self.file_path = file_path
        self.data = []

    def load_data(self):
        with open(self.file_path, 'r') as file:
            for line in file:
                row = line.strip().split(',')
                self.data.append(row)
        return self.…
12 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 easy

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.

adapter design-pattern oop
Python
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_…
13 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 easy

Python object equality: id vs value comparison

Demonstrates the difference between default identity comparison and custom equality, with a value-based class implementing __eq__ and __hash__.

oop equality hash
Python
import copy


class IdOnly:
    def __init__(self, name):
        self.name = name


class ValueId:
    def __init__(self, name):
        self.name = name

    def __eq__(self, other):
        return isinstance(other, ValueId) and self.name == other.name

    def __hash__(self):
        return hash(self.name)

    def…
12 0 Open
OOP & classes easy

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.

memory slots class
Python
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", …
12 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 easy

Validate dataclass fields with __post_init__ in Python

Add custom validation to a Python dataclass inside __post_init__, raising ValueError or TypeError for invalid field values.

dataclasses validation post-init
Python
from dataclasses import dataclass, field
from typing import Optional


@dataclass
class Product:
    name: str
    price: float
    quantity: int = 1
    category: Optional[str] = None

    def __post_init__(self):
        if not self.name or not isinstance(self.name, str):
            raise ValueError("name must be a…
11 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.