__hash__
Dunder MethodPython 2.0+Advanced
Returns the hash value; required for dict key or set member
Quick Info
- Documentation
- Official Docs
- Python Version
- 2.0+
Learn by Difficulty
Quick Example
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.
Try in PlaygroundTags
oopmagic-methodprotocolcore