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__()
__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()。