【问题标题】:What are inside the __eq__() method by default默认情况下 __eq__() 方法里面有什么
【发布时间】:2020-01-13 22:17:32
【问题描述】:

我读到了这个(来自here):

用户自定义类默认有__eq__()和__hash__()方法;使用它们,所有对象都比较不相等(除了它们自己),x.__hash__() 返回一个适当的值,使得 x == y 意味着 x 是 y 和 hash(x) == hash(y)。

我想知道__eq__() 方法是否默认定义为:

def __eq__(self, other):
    return hash(self) == hash(other)

【问题讨论】:

  • 那只适用于hashable 的东西。你将如何检查不可散列的东西? :)

标签: python python-3.x


【解决方案1】:

不,更像是:

def __eq__(self, other)
    return self is other

您不能使用hash(),因为不同的对象可能具有相同的哈希值。

【讨论】:

    【解决方案2】:

    您可以阅读以下参考资料:https://eev.ee/blog/2012/03/24/python-faq-equality/

    在您只是尝试比较 2 个对象而不覆盖 eq 的默认方法中,它将查看它们是否是相同的 2 个对象,更像如下:

    def __eq__(self, other)
        return self is other
    

    【讨论】:

      【解决方案3】:

      可以参考existing question

      它解释了如何正确使用__hash__() 和__eq__()

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-04-25
        • 1970-01-01
        • 1970-01-01
        • 2012-02-29
        • 1970-01-01
        • 2021-05-06
        • 2014-04-16
        相关资源
        最近更新 更多