special method
A Python method with a double-underscore name, such as __eq__ or __hash__, that the language calls automatically for built-in operations.
In more detail
Writing __eq__ defines what == means for your class, __hash__ what hash() returns, and __contains__ what the `in` operator does. Python calls them for you, so a class that defines them works with dicts, sets and sorting like a built-in type. Defining __eq__ without __hash__ sets __hash__ to None, making instances unhashable.
Related terms
- class — A blueprint in code that bundles data and the functions that work on it, from which objects are made.
- hash-equals contract — The rule that if two objects are equal, a == b, then their hashes must be equal too, hash(a) == hash(b).
- hashable — Describes a Python object that has a hash value that never changes during its lifetime and can be compared for equality, so it can be a dict key or set member.
Taught in
- Python Dicts And Sets Under The Hood — Algorithms & Data Structures for Working Engineers