比较对象
为了比较自定义类的相等性,你可以通过定义 __eq__ 和 __ne__ 方法来覆盖 == 和 !=。你也可以覆盖 __lt__(<),__le__(<=),__gt__(>)和 __ge__(>)。请注意,你只需要覆盖两个比较方法,Python 可以处理其余的(== 与 not < 和 not > 等相同)
class Foo(object):
def __init__(self, item):
self.my_item = item
def __eq__(self, other):
return self.my_item == other.my_item
a = Foo(5)
b = Foo(5)
a == b # True
a != b # False
a is b # False
请注意,此简单比较假定 other(要比较的对象)是相同的对象类型。与其他类型相比将引发错误:
class Bar(object):
def __init__(self, item):
self.other_item = item
def __eq__(self, other):
return self.other_item == other.other_item
def __ne__(self, other):
return self.other_item != other.other_item
c = Bar(5)
a == c # throws AttributeError: 'Foo' object has no attribute 'other_item'
检查 isinstance() 或类似将有助于防止这种情况(如果需要)。