gpt4 book ai didi

python - 为什么可变内置对象不能在 Python 中进行哈希处理?这样做有什么好处?

转载 作者:太空狗 更新时间:2023-10-30 02:51:24 27 4
gpt4 key购买 nike

我来自 Java,其中甚至可变对象也可以是“可哈希的”。
而我这些天玩 Python 3.x 只是为了好玩。

这是 Python 中 hashable 的定义(来自 Python 词汇表)。

hashable

An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__() method), and can be compared to other objects (it needs an __eq__() method). Hashable objects which compare equal must have the same hash value.

Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally.

All of Python’s immutable built-in objects are hashable; mutable containers (such as lists or dictionaries) are not. Objects which are instances of user-defined classes are hashable by default. They all compare unequal (except with themselves), and their hash value is derived from their id().

我读了它,我在想...仍然...为什么他们不在 Python 中使可变对象变得可散列?例如。使用与用户定义对象相同的默认散列机制,即上面最后两句话所描述的。

Objects which are instances of user-defined classes are hashable by default. They all compare unequal (except with themselves), and their hash value is derived from their id().

这感觉有点奇怪……所以用户定义的可变对象是可散列的(通过这个默认的散列机制)但是内置的可变对象是不可散列的。这不会使事情复杂化吗?我看不出它带来了什么好处,有人可以解释一下吗?

最佳答案

在 Python 中,可变对象可以是可哈希的,但这通常不是一个好主意,因为一般来说,相等性是根据这些可变属性定义的,这会导致各种疯狂的行为。

如果内置可变对象是基于身份进行哈希处理的,就像用户定义对象的默认哈希机制一样,那么它们的哈希值将与它们的相等性不一致。这绝对是个问题。但是,默认情况下,用户定义的对象会根据身份进行比较和散列,因此情况并没有那么糟糕,尽管这组事务不是很有用。

请注意,如果您在用户定义的类中实现 __eq__,则 __hash__ 将设置为 None,从而使类 不可散列

So, from the Python 3 data model documentation :

User-defined classes have __eq__() and __hash__() methods by default; with them, all objects compare unequal (except with themselves) and x.__hash__() returns an appropriate value such that x == y implies both that x is y and hash(x) == hash(y).

A class that overrides __eq__() and does not define __hash__() will have its __hash__() implicitly set to None. When the __hash__() method of a class is None, instances of the class will raise an appropriate TypeError when a program attempts to retrieve their hash value, and will also be correctly identified as unhashable when checking isinstance(obj, collections.abc.Hashable).

关于python - 为什么可变内置对象不能在 Python 中进行哈希处理?这样做有什么好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56012884/

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