OOP & classes
Classes, instances, methods, dataclasses, and object-oriented design in Python.
Design a Data Helper Class in Python
Create a simple Object-Oriented data helper with DataPoint and Dataset classes that store, describe, and summarize coordinate points.
class DataPoint:
def __init__(self, x, y):
self.x = x
self.y = y
self.label = None
def describe(self):
"""Return a human-readable description of the data point."""
base = f"DataPoint(x={self.x}, y={self.y})"
return f"{base}, label='{self.label}'" if self.label e…
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.
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
…
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.
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):
…
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.
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…
How to Copy Class Instances in Python: Shallow vs Deep Copy
Use copy.copy and copy.deepcopy to clone class instances, showing how nested objects are shared or duplicated.
import copy
class Config:
def __init__(self):
self.settings = {"theme": "dark", "language": "en"}
if __name__ == "__main__":
original = Config()
shallow_copy = copy.copy(original)
deep_copy = copy.deepcopy(original)
shallow_copy.settings["theme"] = "light"
deep_copy.settings["them…
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 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)
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.
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)
How to Implement Rich Comparison Ordering in Python Classes
This code demonstrates how to implement rich comparison operators (like <, <=, >, >=, ==, !=) in a Python class by defining __lt__ and __eq__, enabling sorting and ordering of custom objects.
class Task:
def __init__(self, priority, name):
self.priority = priority
self.name = name
def __lt__(self, other):
if not isinstance(other, Task):
return NotImplemented
return self.priority < other.priority
def __eq__(self, other):
if not isinstance(oth…
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.
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…
How to Implement the State Pattern in Python
Implement the State design pattern in Python by delegating behavior to state objects, letting a media player change actions dynamically without if-else chains.
class State:
def play(self, player): pass
def pause(self, player): pass
def stop(self, player): pass
class PlayingState(State):
def play(self, player):
return "Already playing"
def pause(self, player):
player.state = PausedState()
return "Pausing playback"
def stop(self…
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.
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…
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.
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…
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__.
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…
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.
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…
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.