Reference library

OOP & classes

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

44 matches
OOP & classes easy

Add property getter setter validation in Python

Shows how to use @property with a setter to validate values before assigning them in a Python class.

property validation oop
Python
class Temperature:
    def __init__(self, celsius=0):
        self._celsius = celsius  # Use underscore to avoid recursion
    
    @property
    def celsius(self):
        """Getter returns the stored value."""
        return self._celsius
    
    @celsius.setter
    def celsius(self, value):
        """Setter valid…
16 0 Open
OOP & classes easy

Binary Tree Inorder Traversal in Python

Define a TreeNode class and recursively print in-order traversal (left, node, right) of a binary tree.

binary-tree recursion traversal
Python
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


def inorder_traversal(root):
    return inorder_traversal(root.left) + [root.val] + inorder_traversal(root.right) if root else []


if __name__ == "__main__":
    # Build a…
14 0 Open
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 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:
           …
15 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 easy

Filtering data with a Python class helper

A beginner-friendly DataFilter class that filters lists of dictionaries by exact match, greater-than, and substring conditions.

filter oop class
Python
class DataFilter:
    """A beginner-friendly helper to filter lists of dictionaries."""
    
    def __init__(self, data):
        self.data = data
    
    def filter_by(self, key, value):
        """Return items where data[key] == value."""
        return [item for item in self.data if item.get(key) == value]
    
 …
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 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 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 Call a Parent Class __init__ with super() in Python

Shows how to chain __init__ calls through a class hierarchy using super(), so each class sets its own attributes while reusing the parent's initialization logic.

oop inheritance super
Python
class Animal:
    def __init__(self, name, species):
        self.name = name
        self.species = species
        print(f"Animal init: {self.name}, {self.species}")

class Mammal(Animal):
    def __init__(self, name, species, fur_color):
        super().__init__(name, species)
        self.fur_color = fur_color
   …
13 0 Open
OOP & classes easy

How to Convert Data Types in Python with a Helper Class

This code defines a beginner-friendly OOP helper class for common data conversions like string to list, list to dict, JSON string, and CSV row, with an advanced subclass for numeric casting.

oop classes data-conversion
Python
class DataConverter:
    """A beginner-friendly helper class for common data conversions."""
    
    def __init__(self, data):
        self.data = data
    
    def to_list(self):
        """Convert string data (comma-separated) to a list."""
        if isinstance(self.data, str):
            return [item.strip() for…
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 Create Immutable Data Classes with frozen=True in Python

Create immutable data classes in Python using @dataclass(frozen=True) to prevent attribute modifications after instantiation.

dataclass frozen immutable
Python
from dataclasses import dataclass

@dataclass(frozen=True)
class Point:
    x: float
    y: float

    def distance_from_origin(self) -> float:
        return (self.x**2 + self.y**2) ** 0.5

if __name__ == "__main__":
    p = Point(3.0, 4.0)
    print(p)
    print(f"Distance from origin: {p.distance_from_origin():.2f}…
13 0 Open
OOP & classes easy

How to Create Static Methods in a Python Class

Shows how to define and call static methods inside a class using @staticmethod, with utility functions that don't need instance or class state.

static-method oop class
Python
class MathUtils:
    """Utility class demonstrating static methods."""
    
    @staticmethod
    def add(a, b):
        """Return the sum of two numbers."""
        return a + b
    
    @staticmethod
    def multiply(a, b):
        """Return the product of two numbers."""
        return a * b
    
    @staticmethod
…
14 0 Open
OOP & classes easy

How to Create a Data Formatter Class in Python

A beginner-friendly helper class to format lists, dictionaries, and stored records into readable strings.

oop class formatting
Python
class DataFormatter:
    """Helper class for beginners to format common data types."""
    
    def __init__(self, name="data"):
        self.name = name
        self.records = []
    
    def add_record(self, key, value):
        """Add a key-value record to the formatter."""
        self.records.append({"key": key, …
12 0 Open
OOP & classes easy

How to Create a Data Helper Class in Python with OOP

A complete OOP example with User, Post, and Blog classes that manage data relationships and provide clear helper methods.

oop classes data-modeling
Python
class User:
    def __init__(self, name, email):
        self.name = name
        self.email = email
        self.posts = []

    def create_post(self, title, content):
        post = Post(title, content, self)
        self.posts.append(post)
        return post

    def get_post_count(self):
        return len(self.p…
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 easy

How to Create an Immutable Money Class in Python with dataclasses

Define a frozen dataclass Money that holds an amount and currency, enforces non-negative amounts, and supports safe addition across matching currencies.

dataclass immutable money
Python
from dataclasses import dataclass


@dataclass(frozen=True)
class Money:
    amount: float
    currency: str = "USD"

    def __post_init__(self) -> None:
        if self.amount < 0:
            raise ValueError("amount must be non-negative")

    def add(self, other: "Money") -> "Money":
        if self.currency != o…
16 0 Open
OOP & classes easy

How to Define Dataclass Field Defaults in Python

Implement a Python dataclass with default values for simple fields and default factories for mutable collections.

dataclasses oop defaults
Python
from dataclasses import dataclass, field
from typing import List

@dataclass
class Product:
    name: str
    price: float = 0.0
    quantity: int = 0
    tags: List[str] = field(default_factory=list)
    metadata: dict = field(default_factory=dict)

if __name__ == "__main__":
    p1 = Product("Laptop", 999.99, 5)
   …
13 0 Open
OOP & classes easy

How to Define a Simple Class with __init__ and __repr__ in Python

Defines a Person class with __init__ to store name and age, and __repr__ to give a readable string representation.

class oop init
Python
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __repr__(self):
        return f"Person(name='{self.name}', age={self.age})"


if __name__ == "__main__":
    p1 = Person("Alice", 30)
    p2 = Person("Bob", 25)
    print(p1)
    print(p2)
10 0 Open
OOP & classes easy

How to Define a Simple Python Class with __init__ and __repr__

Define a basic Python class with an __init__ method to set instance attributes and a __repr__ method for a readable representation of objects.

classes oop init
Python
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __repr__(self):
        return f"Person(name={self.name!r}, age={self.age!r})"


if __name__ == "__main__":
    person = Person("Alice", 30)
    print(person)
15 0 Open
OOP & classes easy

How to Implement Iterator Protocol on a Custom Class in Python

Create a custom iterable class by defining the __iter__ and __next__ methods, enabling use in for loops and list conversions.

iterator protocol class
Python
class Countdown:
    """Iterator that counts down from start to 0."""

    def __init__(self, start):
        self.start = start
        self.current = start

    def __iter__(self):
        return self

    def __next__(self):
        if self.current < 0:
            raise StopIteration
        value = self.current
 …
12 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.