比較物件
為了比較自定義類的相等性,你可以通過定義 __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() 或類似將有助於防止這種情況(如果需要)。