Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Use __eq__ and __hash__ Together for Hashable Objects

Make custom objects usable as dictionary keys and set members by implementing both __eq__ and __hash__ correctly.

Python practice25 minMagic Methods & Operator OverloadingAdvancedLast updated April 11, 2026

Problem statement

Create a Point class representing a 2D point (x, y). Implement __eq__ so that two Point instances compare equal when their x and y coordinates are equal. Implement __hash__ so that Points that are equal also have equal hash values, enabling their use as keys in dictionaries and elements in sets. Ensure that comparisons with non-Point objects return NotImplemented for __eq__.

Task

Implement equality and hashing for a Point class so that two points with identical coordinates are equal and have the same hash.

Examples

Points compare equal and can be dictionary keys

Input

({Point(2, 3): 'a'})[Point(2, 3)]

Output

a

Point(2, 3) used to index the dictionary must match the key because equality and hash are consistent.

Input format

A single expression will be evaluated. Tests will compare Point instances, use Points inside sets, or use Points as dictionary keys.

Output format

The expression should evaluate to a Python value whose string form is compared to the expected output.

Constraints

x and y can be any hashable values (commonly ints or floats). __eq__ should return NotImplemented when comparing to non-Point types. __hash__ must be implemented to match the equality semantics.

Samples

Sample 1

Input

Point(1,1) == Point(1,1)

Output

True

Points with identical coordinates are equal.