gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 18:30:01 25 4
gpt4 key购买 nike

以下内容来自 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com