【问题标题】:Python TypeError: Unhashable type when inheriting from subclass with __hash__Python TypeError:使用 __hash__ 从子类继承时无法散列的类型
【发布时间】: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


    【解决方案1】:

    __eq__ 规则既适用于没有任何子类实现 __hash__ 的类,也适用于具有带哈希函数的父类的类。如果一个类覆盖了__eq__,它必须在它旁边覆盖__hash__

    要修复您的样本:

    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
        def __hash__(self):
            return hash((self.x, self.y))
    

    【讨论】:

      猜你喜欢
      • 2022-12-05
      • 1970-01-01
      • 1970-01-01
      • 2013-10-22
      • 2013-01-23
      • 2018-03-13
      • 1970-01-01
      • 2018-12-26
      • 1970-01-01
      相关资源
      最近更新 更多