gpt4 book ai didi

python - 在 Python 3 中,frozenset 子类的实例应该是可哈希的吗?

转载 作者:太空宇宙 更新时间:2023-11-03 18:00:07 25 4
gpt4 key购买 nike

根据https://docs.python.org/2/library/stdtypes.html#frozenset ,在 Python 2 中:

The frozenset type is immutable and hashable -- its contents cannot be altered after is created; however, it can be used as a dictionary key or as an element of another set.

但是根据 https://docs.python.org/3.4/library/stdtypes.html#frozenset ,在 Python 3 中,我看不到任何信息表明 freezeset 实例(或子类)应该是可哈希的,只有 set/frozenset 元素:

Set elements, like dictionary keys, must be hashable.

那么,以下代码是否适用于任何 Python 3 解释器,或者最后一行是否应该引发 TypeError

# Code under test
class NewFrozenSet(frozenset):
def __eq__(self, other):
return True

# Workaround: Uncomment this override
# def __hash__(self):
# return hash(frozenset(self))

hash(frozenset())
hash(NewFrozenSet())

OSX Yosemite 10.10,系统python2

$ python
Python 2.7.6 (default, Sep 9 2014, 15:04:36)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> class NewFrozenSet(frozenset):
... def __eq__(self, other):
... return True
...
>>> hash(frozenset())
133156838395276
>>> hash(NewFrozenSet())
133156838395276

OSX Yosemite 10.10,使用自制软件 http://brew.sh/

$ brew install python3
$ python3
Python 3.4.2 (default, Jan 5 2015, 11:57:21)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> class NewFrozenSet(frozenset):
... def __eq__(self, other):
... return True
...
>>> hash(frozenset())
133156838395276
>>> hash(NewFrozenSet())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'NewFrozenSet'
>>>

Ubuntu 14.04.1 LTS (x86_64),系统 python3

$ python3
Python 3.4.0 (default, Apr 11 2014, 13:05:11)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> class NewFrozenSet(frozenset):
... def __eq__(self, other):
... return True
...
>>> hash(frozenset())
133156838395276
>>> hash(NewFrozenSet())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'NewFrozenSet'
>>>

TL;DR - 这是 Python 3 中的回归,还是有意的设计选择?

最佳答案

来自 hashable 的定义:

Hashable objects which compare equal must have the same hash value.

您现在已经为 NewFrozenSet 实现了新的 __eq__ 方法,但还没有实现新的 __hash__。 Python 现在不能假设上述属性成立(即 __eq__ 和 __hash__ 的行为匹配),因此它不能假设该类型是可哈希的。这就是为什么您需要同时实现 __eq____hash__ 以使类型可哈希(或者不实现其中任何一个并使用父类中的方法)。

例如,如果您省略 __eq__,则 NewFrozenSet 确实会变得可哈希:

class NewFrozenSet(frozenset):
pass

如果这在您的 NewFrozenSet 中不正确,那么您需要同时实现 __eq____hash__

关于python - 在 Python 3 中,frozenset 子类的实例应该是可哈希的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27831860/

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