python - 为什么 Sets 允许多个具有不同 hashCode 的相同对象?

标签 python python-3.x set hashcode

根据我的理解,集合中的每个对象只能有一个。但我发现以下示例,其中一个集合有两个相同的对象

class myObject:

    def __init__(self, x):
        self.x = x

    def set(self, x):
        self.x = x

    def __hash__(self):
        return self.x

    def __eq__(self, o):
        return self.x == o.x

    def __str__(self):
        return str(self.x)

    def __repr__(self):
        return str(self.x)

当我运行以下命令时:

x = myObject(1)

mySet = {x}

x.set(2)
mySet.add(x)

print(mySet)

x.set(3)

print(mySet)

我得到以下输出:

{2, 2}
{3, 3}

如果我删除 __str____repr__ 方法,它会显示集合中有两个对象具有相同的内存地址:

{<__main__.myObject object at 0x10e3a10d0>, <__main__.myObject object at 0x10e3a10d0>}

我知道Python不允许像列表这样的东西被散列,因为散列码可能会改变,导致与上面显示的类似的错误。为什么 Python 允许这样做,但不允许列表等。当然 Python 也应该有某种方法来管理不断变化的哈希值。

我在java上测试了同样的例子,同样的事情发生了。为什么这些语言允许这样做?

最佳答案

这里有一个指向文档的链接,它解决了哈希问题

什么是哈希:https://docs.python.org/3/reference/datamodel.html#object.hash

什么是可哈希的(重要):https://docs.python.org/3/glossary.html#term-hashable

"An object is hashable if it has a hash value which never changes during its lifetime..."

修改 x 后查看设置对象本身。

s = set()
x = myObject(2)

然后查看集合成员的哈希:

enter image description here

然后:

x.set(4)

enter image description here

没有变化。事实上,如果您继续在其他地方使用该集合(例如 fs = freezeset(s)),您将继续传递旧的哈希值。

关于python - 为什么 Sets 允许多个具有不同 hashCode 的相同对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58261388/

相关文章:

java - Hibernate PersistentSet remove() 操作不起作用

java - 如何制作由 map 支持的集合?

python - 如何替换 pandas 中的间隙行

python - 删除 UserProfile 时删除用户

python-3.x - 将 pydub 输出从 azure 流式传输到本地计算机

python - AttributeError: 'Series' 对象没有属性 'reshape'

python asyncio解释和信号处理程序

python - 用相应的工作日数字替换列表中的工作日字符串 ("MON"、 "TUE"等)

python - 是否有使用 Sqlite 的 "with conn.cursor() as..."方法?

algorithm - 收集一组项目的优化算法