Reference library

OOP & classes

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

10 matches
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 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 a Context Manager Class in Python

Create a reusable context manager class that opens and automatically closes resources using the with statement.

context-manager with-statement resource-management
Python
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…
12 0 Open
OOP & classes easy

How to Build a Data Helper Class in Python with OOP

Create a beginner-friendly Python class that loads CSV data, filters records by field, and counts entries using object-oriented programming.

oop csv data
Python
class DataHelper:
    """A beginner-friendly OOP helper for handling simple datasets."""
    
    def __init__(self, filename):
        self.filename = filename
        self.data = self._load_data()
    
    def _load_data(self):
        """Load data from a CSV file into a list of dictionaries."""
        import csv
 …
12 0 Open
OOP & classes easy

How to Build a Fluent Interface with the Builder Pattern in Python

Learn to implement a fluent builder pattern in Python by chaining methods that return self, enabling readable object construction.

builder fluent oop
Python
class Pizza:
    def __init__(self):
        self.size = None
        self.toppings = []
        self.crust = None

    def set_size(self, size):
        self.size = size
        return self

    def add_topping(self, topping):
        self.toppings.append(topping)
        return self

    def set_crust(self, crust):
…
15 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 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 Create an Iterable Class with __iter__ and __next__ in Python

Build custom iterable classes in Python by implementing the __iter__ and __next__ dunder methods to yield items on demand.

iterable iterator dunder-methods
Python
class EvenNumbers:
    def __init__(self, limit):
        self.limit = limit
        self.current = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.current >= self.limit:
            raise StopIteration
        result = self.current
        self.current += 2
        return resul…
14 0 Open
OOP & classes easy

How to Implement a Queue Class in Python Using deque

Build a FIFO queue class in Python backed by the collections.deque container with enqueue, dequeue, peek, and size methods.

queue deque data-structures
Python
from collections import deque

class Queue:
    def __init__(self):
        self._items = deque()
    
    def enqueue(self, item):
        self._items.append(item)
    
    def dequeue(self):
        if self.is_empty():
            raise IndexError("dequeue from empty queue")
        return self._items.popleft()
    …
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.