我有一个类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

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__
添加回答
举报
0/150
提交
取消