为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

叮当猫咪 2019-10-05 15:13:13
我有一个类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 == yFalse如何让python认为这两个对象相等?
查看完整描述

3 回答

?
蝴蝶刀刀

TA贡献1801条经验 获得超8个赞

您将覆盖对象中的丰富比较运算符。


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


查看完整回答
反对 回复 2019-10-05
?
qq_花开花谢_0

TA贡献1835条经验 获得超7个赞

__eq__在您的课程中实现该方法;像这样的东西:


def __eq__(self, other):

    return self.path == other.path and self.title == other.title

编辑:如果您希望对象比较且仅当它们具有相等的实例字典时才比较:


def __eq__(self, other):

    return self.__dict__ == other.__dict__


查看完整回答
反对 回复 2019-10-05
  • 3 回答
  • 0 关注
  • 830 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信