python - 与 Python 3.1 文档相反,hash(obj) != id(obj)。那么哪个是正确的?

标签 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).

来自词汇表:

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 中更改。

最佳答案

我猜这是 Python 3.x 中为提高性能所做的更改。查看issue 5186 ,然后仔细查看不匹配的数字:

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

这可能值得作为文档错误报告。

关于python - 与 Python 3.1 文档相反,hash(obj) != id(obj)。那么哪个是正确的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3027838/

相关文章:

c++ - 如何在 Cython 中声明指针 vector ?

python - 使用 Openpyxl 将单元格分配给变量

c - 验证某个键是否在哈希表中

ruby-on-rails - 使用键的值作为同一散列中另一个键的值的一部分

python - 在 Python 中打印表格数据

python - Django - 有没有办法在我的项目的 signals.py 文件中获取当前登录的用户?

python - 如何更改 Google 表格电子表格的所有者?

Python字典键(类对象)与多个比较器的比较

c# - SHA256 支持整数吗?

ruby - 为什么哈希字面量在 Ruby 中被称为哈希字面量?