与Python 3.1 Docs相反,hash(obj)!= id(obj).哪个是正确的?

Don*_*ell 10 python hash

以下内容来自Python v3.1.2文档:

来自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).
Run Code Online (Sandbox Code Playgroud)

来自词汇表:

hashable

... Objects which are instances of user-defined classes are 
hashable by default; they all compare unequal, and their hash 
value is their id().
Run Code Online (Sandbox Code Playgroud)

从版本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
Run Code Online (Sandbox Code Playgroud)

但在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
Run Code Online (Sandbox Code Playgroud)

那是哪个呢?我应该报告文档错误或程序错误吗?如果它是文档错误,并且hash()用户类实例的默认值不再与该id()值相同,那么知道它是什么或如何计算以及它在版本3中的更改原因会很有趣.

ʇsә*_*ɹoɈ 10

我猜这是在Python 3.x中进行的一项改进,以提高性能.查看问题5186,然后仔细查看不匹配的数字:

>>> bin(11893680)
'0b101101010111101110110000'
>>> bin(743355)
'0b10110101011110111011'
>>> 11893680 >> 4
743355
Run Code Online (Sandbox Code Playgroud)

作为文档错误,它可能值得报告.