【发布时间】:2022-12-03 12:38:23
【问题描述】:
我有一个基类和一个子类,例如:
class Base:
def __init__(self, x):
self.x = x
def __eq__(self, other):
return self.x == other.x
def __hash__(self):
return hash(self.x)
class Subclass(Base):
def __init__(self, x, y):
super().__init__(x)
self.y = y
def __eq__(self, other):
return self.x == other.x and self.y == other.y
由于父类实现了__hash__,所以它应该是可哈希的。但是,当我尝试将两个副本放入一个集合中时,例如 {Subclass(1, 2), Subclass(1, 3)},我收到此错误:
TypeError: unhashable type: 'Subclass'
我知道如果一个对象实现了 __eq__ 但没有实现 __hash__ 那么它会抛出 TypeError,但是有一个明确实现的哈希函数。这是怎么回事?
【问题讨论】:
标签: python python-3.x