What does “hashable” mean in Python?

后端 未结 9 887
挽巷
挽巷 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:30

    Anything that is not mutable (mutable means, likely to change) can be hashed. Besides the hash function to look for, if a class has it, by eg. dir(tuple) and looking for the __hash__ method, here are some examples

    #x = hash(set([1,2])) #set unhashable
    x = hash(frozenset([1,2])) #hashable
    #x = hash(([1,2], [2,3])) #tuple of mutable objects, unhashable
    x = hash((1,2,3)) #tuple of immutable objects, hashable
    #x = hash()
    #x = hash({1,2}) #list of mutable objects, unhashable
    #x = hash([1,2,3]) #list of immutable objects, unhashable
    

    List of immutable types:

    int, float, decimal, complex, bool, string, tuple, range, frozenset, bytes
    

    List of mutable types:

    list, dict, set, bytearray, user-defined classes
    

提交回复
热议问题