python中的hashable(可哈希的)是什么意思

不严谨但简单的理解:

一个对象在其生命周期内,如果保持不变,就是hashable(可哈希的)。

hashable ≈ imutable     可哈希 ≈ 不可变

在Python中:

list、set和dictionary 都是可改变的,比如list.append(),set.remove(),dict['key'] = value,是不可哈希的;

而tuple和string是不可变的,只可以做复制或者切片等操作,这就是可哈希的。

官方但准确的解释:

An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__() method), and can be compared to other objects (it needs an __eq__() or __cmp__() method). Hashable objects which compare equal must have the same hash value.

Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally.

All of Python’s immutable built-in objects are hashable, while no mutable containers (such as lists or dictionaries) are. Objects which are instances of user-defined classes are hashable by default; they all compare unequal, and their hash value is their id().

大致翻译一下:

如果一个对象在其生命周期内,其哈希值从未改变(这需要一个__hash__()方法),并且可以与其他对象进行比较(这需要一个__eq__()或__cmp__()方法),那么这个对象就是可哈希的。哈希对象的相等意味着其哈希值的相等。

哈希性使得对象可以用作dictionary键和set成员,因为这些数据结构在内部使用了哈希值。

Python的所有不可变的内置对象都是可hashable的,但可变容器(如列表或字典)并非如此。对于用户定义的类的实例,默认情况下是可哈希的;它们都是不相等的,并且它们的哈希值都是id()。

猜你喜欢

转载自blog.csdn.net/qq_17753903/article/details/85345996