python 中倒是什麽事可哈希的意思那?
可哈希對象
python中的hashable(可哈希的)是什麽意思
2018年12月29日 23:29:36 shangyj17 閱讀數:511不嚴謹但易懂的解釋:
一個對象在其生命周期內,如果保持不變,就是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()。
hashable
如果一個對象是可哈希的,那麽它就有一個在其生命周期中都不會改變的哈希值,它會有一個__hash__()方法,它要能夠和其他對象比較(需要__eq__()方法或__cmp__()方法)。可哈希對象相同要求哈希值相同。
不可哈希
list, set, dict
可哈希
數值,字符串,boolean
對象可不可hash?
class A:
def __init__(self):
pass
a = A()
print hash(a)
實驗發現對象是可哈希的,為啥呢?因為所有對象都繼承自object,而object有__hash__方法。bingo!
等等!不是說python一切皆對象麽?
>>> issubclass(int, object)
True
>>> issubclass(list, object)
True
抱著試一試的態度,我查看了一下list,發現也有__hash__方法。但是list不是不可哈希的麽??於是我們打印出__hash__看一看。
print object.__hash__
# <slot wrapper ‘__hash__‘ of ‘object‘ objects>
print int.__hash__
# <slot wrapper ‘__hash__‘ of ‘int‘ objects>
print list.__hash__
# None
哈哈,這下清楚了,雖然list也有__hash__屬性,但是是None,同樣dict和set的__hash__也是None。想知道一個對象是不是可哈希,只要看__hash__是不是None。
不要相信我,相信自己的代碼
class A:
def __init__(self):
self.__hash__ = None
a = A()
print hash(a)
現在a對象已經不可哈希了。
轉發https://www.jianshu.com/p/1a05bd66936a
https://blog.csdn.net/qq_17753903/article/details/85345996
python 中倒是什麽事可哈希的意思那?