33. Python's Built-in Hash Functions
In Python, hashable objects are objects that can be used as keys in dictionaries or added to sets. To make a class hashable, you must implement the __hash__ and __eq__ methods in the class. The __hash__ method returns an integer, which is used to quickly compare and look up objects in hash-based containers like dictionaries and sets. The __eq__ method is used to check if two objects are equal.
Here are 10 Python code snippets that demonstrate how to create hashable objects using built-in hash functions:
1. Basic Hashable Object
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __hash__(self):
return hash((self.name, self.age))
def __eq__(self, other):
return (self.name, self.age) == (other.name, other.age)
# Usage
person1 = Person("Alice", 30)
person2 = Person("Alice", 30)
person3 = Person("Bob", 25)
# Using the objects in a set
people_set = {person1, person2, person3}
print(people_set) # Outputs: {<__main__.Person object at 0x...>, <__main__.Person object at 0x...>}2. Hashable Object with Tuple
3. Hashable Object with Immutable Attributes
4. Custom Hashable Class Using __slots__
5. Hashable Object with Custom __repr__
6. Hashable Object with Custom Attributes
7. Hashable Class Using frozenset
8. Hashable Object with Default Dictionary Behavior
9. Hashable Object with __eq__ and __ne__
10. Hashable Object with Multiple Attributes
These examples show how to make custom objects hashable by implementing the __hash__ and __eq__ methods. This allows objects to be used in hash-based containers such as dictionaries and sets, which rely on hashing for fast lookups.
Last updated