跳到内容

eq-without-hash (PLW1641)

源自 Pylint 代码检查工具。

作用

检查实现了 __eq__ 但未实现 __hash__ 的类。

为什么这不好?

一个实现了 __eq__ 但未实现 __hash__ 的类,其哈希方法将被隐式设置为 None,无论父类是否定义了 __hash__。这将导致该类不可哈希,进而导致在使用该类的实例作为字典中的键或集合的成员时出现问题。

示例

class Person:
    def __init__(self):
        self.name = "monty"

    def __eq__(self, other):
        return isinstance(other, Person) and other.name == self.name

建议改为

class Person:
    def __init__(self):
        self.name = "monty"

    def __eq__(self, other):
        return isinstance(other, Person) and other.name == self.name

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

通常,在重写 __eq__ 实现的同时从父类继承 __hash__ 实现是不合理的,因为两者必须保持同步。但是,在这种情况下,解决此错误的简单方法是显式地将 __hash__ 设置为父类的实现,在确实合理的情况下。

class Developer(Person):
    def __init__(self): ...

    def __eq__(self, other): ...

    __hash__ = Person.__hash__

参考