[英]__hash__ method and documentation. Probable error?
閱讀文檔
object.__hash__(self)
由內置函數
hash()
調用,並用於對哈希集合的成員(包括set,Frozenset和dicthash()
進行操作。 [...]
和....
Python的所有不可變內置對象都是可哈希的,而沒有可變容器(例如list或dictionaries )是可哈希的。
從控制台:
>>> a = {'name': 'abcdef'}
>>> hash(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'
通過這種方式,我了解到dict對象是不可哈希的,那么為什么文檔說我可以在dict對象上調用哈希函數?
由內置函數hash()調用,用於散列集合的成員 (包括set,frozenset和dict)上的操作。 [...]
__hash__
在集合成員(或鍵)上調用,而不在集合本身上調用。
您誤讀了文檔。
內置函數hash()
可以對 object.__hash__
進行[c]處理,並且可以對散列集合的成員(包括set,frozenset和dict hash()
進行操作。
__hash__
不在 dict
調用。 它被稱為dict
成員 。
演示:
>>> class Hashable(object):
... def __hash__(self):
... print '__hash__ was called'
... return super(Hashable, self).__hash__()
...
>>> {Hashable(): None}
__hash__ was called
{<__main__.Hashable object at 0x10bce7750>: None}
由於Hashable()
實例用作鍵, __hash__
在創建字典時將調用其__hash__
方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.