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 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 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.
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()
…
How to Lazy Load an Expensive Attribute with a Proxy in Python
This code shows a Proxy class that lazily loads an ExpensiveResource only when first accessed, caching it for subsequent uses.
class ExpensiveResource:
def __init__(self, name):
self.name = name
print(f"Expensive resource '{name}' created (e.g., DB connection)")
def use(self):
return f"Using {self.name}"
class Proxy:
def __init__(self, name):
self._name = name
self._resource = None
@p…
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.
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…
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…
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.