2010-06-12 31 views
10

下面是從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中發生了變化。

+0

不確定StackOverflow是否是正確的地方... – Artelius 2010-06-12 07:18:21

+0

請注意,CPython 2.6中的'x .__ hash __()== id(x)'不一定是真的:在一個平臺上(例如64位置Windows),其中'id'值大於'LONG_MAX'是可能的,'id(x)'值可以被截斷以給出散列。 – 2010-06-12 11:17:10

回答

10

我猜這是爲了提高性能而在Python 3.x中做出的更改。退房issue 5186,然後尋找更貼切一點在你不匹配的數字:

>>> bin(11893680) 
'0b101101010111101110110000' 
>>> bin(743355) 
'0b10110101011110111011' 
>>> 11893680 >> 4 
743355 

這可能是值得報告的文檔錯誤。

+0

+1。絕對值得報道。 – 2010-06-12 10:43:24

+0

回答所有問題,還有更多。謝謝。 – 2010-06-12 14:54:27

相關問題