__hash__ — Easy Examples
Returns the hash value; required for dict key or set member
Implementing __hash__
Basic implementation of __hash__ in a class.
python
class Color: def __init__(self, r, g, b): self.r = r self.g = g self.b = b def __hash__(self): return hash((self.r, self.g, self.b)) def __eq__(self, other): return (self.r, self.g, self.b) == (other.r, other.g, other.b) colors = {Color(255, 0, 0): "red", Color(0, 255, 0): "green"} print(colors[Color(255, 0, 0)])
__hash__ returns the hash value; required for dict key or set member. Implementing it lets you customize how Python interacts with your objects.
__hash__ in action
Seeing __hash__ called by Python's built-in operations.
python
# How Python calls __hash__ automatically class Demo: def __init__(self, value): self.value = value def __hash__(self): print(f"__hash__ was called!") return self d = Demo(42) # This triggers __hash__: print(hash(d))
Python automatically calls __hash__ when you use the corresponding operator or function on your object.
Want to try these examples interactively?
Open Easy Playground