What does “hashable” mean in Python?

后端 未结 9 870
挽巷
挽巷 2020-11-22 16:45

I tried searching internet but could not find the meaning of hashable.

When they say objects are hashable or hashable objects what does it

9条回答
  •  孤城傲影
    2020-11-22 17:37

    In my understanding according to Python glossary, when you create a instance of objects that are hashable, an unchangeable value is also calculated according to the members or values of the instance. For example, that value could then be used as a key in a dict as below:

    >>> tuple_a = (1,2,3)
    >>> tuple_a.__hash__()
    2528502973977326415
    >>> tuple_b = (2,3,4)
    >>> tuple_b.__hash__()
    3789705017596477050
    >>> tuple_c = (1,2,3)
    >>> tuple_c.__hash__()
    2528502973977326415
    >>> id(a) == id(c)  # a and c same object?
    False
    >>> a.__hash__() == c.__hash__()  # a and c same value?
    True
    >>> dict_a = {}
    >>> dict_a[tuple_a] = 'hiahia'
    >>> dict_a[tuple_c]
    'hiahia'
    

    we can find that the hash value of tuple_a and tuple_c are the same since they have the same members. When we use tuple_a as the key in dict_a, we can find that the value for dict_a[tuple_c] is the same, which means that, when they are used as the key in a dict, they return the same value because the hash values are the same. For those objects that are not hashable, the method hash is defined as None:

    >>> type(dict.__hash__) 
    
    

    I guess this hash value is calculated upon the initialization of the instance, not in a dynamic way, that's why only immutable objects are hashable. Hope this helps.

提交回复
热议问题