Reference library

OOP & classes

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

8 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…
14 0 Open
OOP & classes easy

Graph Class with Adjacency Dict in Python

Build an undirected graph class using a dictionary of adjacency lists with methods to add vertices, edges, remove edges, and query neighbors.

graph oop adjacency-list
Python
class Graph:
    def __init__(self):
        self.adjacency = {}

    def add_vertex(self, vertex):
        if vertex not in self.adjacency:
            self.adjacency[vertex] = []

    def add_edge(self, u, v):
        self.add_vertex(u)
        self.add_vertex(v)
        self.adjacency[u].append(v)
        self.adja…
12 0 Open
OOP & classes easy

How to Build a Class Method Alternative Constructor from Dict in Python

Use a classmethod alternative constructor to build a Book instance from a dictionary with sensible defaults.

classmethod alternate-constructor oop
Python
class Book:
    def __init__(self, title, author, pages):
        self.title = title
        self.author = author
        self.pages = pages

    @classmethod
    def from_dict(cls, data):
        """Alternative constructor that builds a Book from a dictionary."""
        return cls(
            title=data["title"],
 …
15 0 Open
OOP & classes easy

How to Build an In-Memory CRUD Repository Class in Python

Define a Python Repository class that stores objects in a dictionary and supports create, read, update, delete, and list operations.

repository crud oop
Python
class Repository:
    def __init__(self):
        self._data = {}

    def create(self, key, value):
        self._data[key] = value
        return key

    def read(self, key):
        return self._data.get(key)

    def update(self, key, value):
        if key not in self._data:
            raise KeyError(f"Key '{ke…
14 0 Open
OOP & classes easy

How to Count Items in a Python Class

A beginner-friendly Inventory class that stores item quantities in a dictionary and provides add, remove, count, and summary methods.

oop classes inventory
Python
class Inventory:
    def __init__(self):
        self.items = {}

    def add(self, item, quantity=1):
        self.items[item] = self.items.get(item, 0) + quantity

    def remove(self, item, quantity=1):
        if item not in self.items:
            raise ValueError(f"{item} not in inventory")
        self.items[it…
13 0 Open
OOP & classes easy

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.

oop hashable eq
Python
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…
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 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

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.