Reference library

OOP & classes

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

2 matches
OOP & classes easy

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.

oop hashable eq
Python
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…
13 0 Open
OOP & classes easy

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__.

oop equality hash
Python
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…
12 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.