34. Custom Hashable Classes
1. Basic Hashable Class
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __eq__(self, other):
return (self.name, self.age) == (other.name, other.age)
def __hash__(self):
return hash((self.name, self.age))
# Create instances
p1 = Person("Alice", 30)
p2 = Person("Alice", 30)
# Use in a set
people = {p1, p2}
print(len(people)) # Output: 1, since p1 and p2 are considered equal2. Hashable with Mutable Fields
3. Using frozenset for Nested Objects
frozenset for Nested Objects4. Hashable with Tuple Field
5. Hashable with __slots__
__slots__6. Hashable with Multiple Attributes
7. Custom Hashing Algorithm
8. Handling Mutable and Immutable Types Together
9. Immutable Class with NamedTuple
NamedTuple10. Custom Hash with Cache
Last updated