gpt4 book ai didi

python - 继承 - __hash__ 在子类中设置为 None

转载 作者:太空宇宙 更新时间:2023-11-03 13:27:05 24 4
gpt4 key购买 nike

我设法在 Python 3.4 和 3.7 上重现了这一点。

考虑:

class Comparable:
def _key(self):
raise NotImplementedError

def __hash__(self):
return hash(self._key())

def __eq__(self, other):
...

def __lt__(self, other):
...


class A(Comparable): pass

class B(A):
def __str__(self):
return "d"

def __eq__(self, other):
return isinstance(self, type(other))

def _key(self):
return str(self),

b = B()

很明显,人们会期望 b.__hash__ 在这里定义,因为它是在 Comparable 下定义的,BB 的子类。

瞧,它已被定义,但计算结果为 None。给了什么?

>> b
<__main__.B object at 0x00000183C9734978>
>> '__hash__' in dir(b)
True
>> b.__hash__

>> b.__hash__ is None
True
>> B.__mro__
(<class '__main__.B'>, <class '__main__.A'>, <class '__main__.Comparable'>, <class 'object'>)
>> isinstance(b, Comparable)
True

如果在 ComparableA 中将 __init__ 实现为 super().__init__(),则会重现相同的行为>.

最佳答案

the docs 中找到它:

A class that overrides __eq__() and does not define __hash__() will have its __hash__() implicitly set to None.

If a class that overrides __eq__() needs to retain the implementation of __hash__() from a parent class, the interpreter must be told this explicitly by setting __hash__ = <ParentClass>.__hash__

来自工单 1549 :

This was done intentionally -- if you define a comparison without defining a hash, the default hash will not match your comparison, and your objects will misbehave when used as dictionary keys.

(圭多范罗森)

关于python - 继承 - __hash__ 在子类中设置为 None,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53518981/

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