Hash() Function In Python

Overview of Hash Value and Hash functions:

A hash value is an integer to uniquely identify objects in the Python environment. Typically, hash values are provided by hash function(s) that take one or more attributes of an object and return an integer that identifies the object.  The hash value is used to compare two objects and assert whether the objects under comparison are the same.

Containers like dict, set use hash values in their lookup operations. With keys of the containers stored using the hash values, lookup operations are possible with lookup times of O(1). The hash function is the one that ensures the hash values of the objects are far apart so that they are unique and do not collide.

Python provides a built-in hash function hash() which return the hash value for any object passed as a parameter. For user defined objects the hash() function calls the __hash__() method of the corresponding class.

Only immutable objects should have the __hash()__ method defined.

Otherwise storage and retrieval of python objects in containers like dict, set is not possible.

Method Name:

hash(object)

Method overview:

The hash() function takes a python object as input and returns the hash value. The returned hash value would change between multiple runs of Python because of security reasons. This behavior is controlled by the environment variable PYTHONHASHSEED.

Example Python Program using hash() function:

class Emp:

    def __init__(self, aId_in, aName_in):

        self.myId = aId_in

        self.myName = aName_in

       

    def __hash__(self):

        h = hash("{}.{}".format(self.myId,self.myName))

        return h

 

Emp1 = Emp(12345, "Ada")

print("Hash Value of object1 {}".format(hash(Emp1)))

 

Emp2 = Emp(12346, "Ritchie")

print("Hash Value of object2 {}".format(hash(Emp2)))

 

 

 

Output of Example Python Program that uses the hash() function:

Hash Value of object1 8750039985873350939

Hash Value of object2 -1514168357917997398

 

 


Copyright 2023 © pythontic.com