OOP & classes
Classes, instances, methods, dataclasses, and object-oriented design in Python.
How to Compare Dataclass Instances by Specific Fields in Python
Use @dataclass(order=True) with field(compare=False) to control which fields determine ordering and equality between instances.
from dataclasses import dataclass, field
from typing import Any
@dataclass(order=True)
class Person:
name: str = field(compare=False)
age: int
height_cm: float
priority: int = field(compare=False, default=0)
def __repr__(self):
return f"Person(name={self.name!r}, age={self.age}, height={s…
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 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)]
…
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.
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…
How to Sort Data in Python with a Class Helper
This beginner-friendly class wraps the built-in sorted() function to sort numbers, strings ignoring case, and dictionaries by a specified key.
class DataSorter:
def __init__(self, data):
self.data = data
def sort_numbers(self, reverse=False):
return sorted(self.data, reverse=reverse)
def sort_strings_ignore_case(self, reverse=False):
return sorted(self.data, key=str.lower, reverse=reverse)
def sort_dicts_by_key(self…
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.
```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…
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.
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 …
Python Abstract Class with Concrete Subclasses
Define an abstract base class with abstract methods and implement them in concrete subclasses like Rectangle and Circle.
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…
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.
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…
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.