猿问

通过Python中对象实例的属性比较对象实例是否相等

我有一个类MyClass,其中包含两个成员变量foo和bar:


class MyClass:

    def __init__(self, foo, bar):

        self.foo = foo

        self.bar = bar

我有这样的类,其每个具有相同值的两个实例foo和bar:


x = MyClass('foo', 'bar')

y = MyClass('foo', 'bar')

但是,当我比较它们的相等性时,Python返回False:


>>> x == y

False

如何让python认为这两个对象相等?


叮当猫咪
浏览 831回答 3
3回答

蝴蝶刀刀

您将覆盖对象中的丰富比较运算符。class MyClass: def __lt__(self, other):      # return comparison def __le__(self, other):      # return comparison def __eq__(self, other):      # return comparison def __ne__(self, other):      # return comparison def __gt__(self, other):      # return comparison def __ge__(self, other):      # return comparison像这样:    def __eq__(self, other):        return self._id == other._id

qq_花开花谢_0

__eq__在您的课程中实现该方法;像这样的东西:def __eq__(self, other):    return self.path == other.path and self.title == other.title编辑:如果您希望对象比较且仅当它们具有相等的实例字典时才比较:def __eq__(self, other):    return self.__dict__ == other.__dict__
随时随地看视频慕课网APP

相关分类

Python
我要回答