PYTHON
Making Custom Python Objects Hashable for Collections
Implement `__hash__` and `__eq__` methods to enable custom Python objects to be used as keys in dictionaries or elements in sets.
class Coordinate:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
"""
Defines equality comparison for Coordinate objects.
Required for hashable objects to ensure two equal objects have the same hash.
"""
if not isinstance(other, Coordinate):
return NotImplemented
return self.x == other.x and self.y == other.y
def __hash__(self):
"""
Defines the hash value for Coordinate objects.
Must be consistent with __eq__.
"""
return hash((self.x, self.y)) # Hash of a tuple of immutable attributes
def __repr__(self):
return f"Coordinate({self.x}, {self.y})"
# Example Usage
coord1 = Coordinate(1, 2)
coord2 = Coordinate(1, 2)
coord3 = Coordinate(3, 4)
# Use as dictionary keys
coord_dict = {coord1: "Home", coord3: "Work"}
print(f"Value for coord1: {coord_dict[coord2]}") # Accessing with an equal object
# Use in a set
unique_coords = {coord1, coord2, coord3}
print(f"Unique coordinates in set: {unique_coords}") # Only 2 unique objects due to __eq__ and __hash__
# Demonstrating equality
print(f"coord1 == coord2: {coord1 == coord2}")
print(f"coord1 == coord3: {coord1 == coord3}")
How it works: This snippet shows how to make custom Python objects hashable, allowing them to be used as keys in dictionaries or elements in sets. This requires implementing both the `__eq__` (equality) and `__hash__` (hashing) special methods. `__eq__` defines when two objects are considered equal, while `__hash__` returns an integer hash value. Crucially, if two objects are equal (`__eq__` returns True), their `__hash__` values *must* be identical.