【发布时间】:2023-03-26 13:14:01
【问题描述】:
在将某些代码从 python 2 转换到 python 3 时,我遇到了一个奇怪的行为示例。下面是它的最小 (?) 示例:
class Bar(object):
def __init__(self, x):
self.x = x
def __eq__(self, other):
return self.x == other.x
b = Bar(1)
print(hash(b))
当使用python2 运行时,此代码会产生一些输出(Bar(1) 的哈希),而python3 会产生TypeError: unhashable type: 'Bar'
这意味着 __hash__ 在 python 2 中以某种方式继承(从 object ?)。
所以,我的问题是:Bar(1) 在 python 2 中的哈希是什么?为什么行为不同?
【问题讨论】: