下面是從Python V3.1.2文檔:與Python 3.1 Docs相反,hash(obj)!= id(obj)。那麼哪個是正確的?
從Python語言參考第3.3.1節基本定製:
object.__hash__(self)
... User-defined classes have __eq__() and __hash__() methods
by default; with them, all objects compare unequal (except
with themselves) and x.__hash__() returns id(x).
從名詞解釋:
hashable
... Objects which are instances of user-defined classes are
hashable by default; they all compare unequal, and their hash
value is their id().
這是真的通過版本2.6.5:
Python 2.6.5 (r265:79096, Mar 19 2010 21:48:26) ...
...
>>> class C(object): pass
...
>>> c = C()
>>> id(c)
11335856
>>> hash(c)
11335856
但在版本3.1.2中:
Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) ...
...
>>> class C: pass
...
>>> c = C()
>>> id(c)
11893680
>>> hash(c)
743355
那麼這是哪一個呢?我應該報告文檔錯誤還是程序錯誤? 如果這是一個文檔錯誤,並且用戶的默認hash()
值 類實例不再與id()
值相同,那麼知道它是什麼或它是如何計算的以及爲什麼它是 在版本3中發生了變化。
不確定StackOverflow是否是正確的地方... – Artelius 2010-06-12 07:18:21
請注意,CPython 2.6中的'x .__ hash __()== id(x)'不一定是真的:在一個平臺上(例如64位置Windows),其中'id'值大於'LONG_MAX'是可能的,'id(x)'值可以被截斷以給出散列。 – 2010-06-12 11:17:10