Python比较对象
示例
为了比较自定义类的相等性,可以重写==和!=通过定义__eq__和__ne__方法。您也可以覆盖__lt__(<),__le__(<=),__gt__(>)和__ge__(>)。请注意,您只需要重写两个比较方法,Python即可处理其余的比较方法(==与not<和not>等相同)。
class Foo(object):
def __init__(self, item):
self.my_item= item
def __eq__(self, other):
returnself.my_item== other.my_item
a = Foo(5)
b = Foo(5)
a == b #真正
a != b #假
a is b #假注意,此简单比较假定other(要比较的对象)是相同的对象类型。与其他类型比较会抛出错误:
class Bar(object):
def __init__(self, item):
self.other_item= item
def __eq__(self, other):
returnself.other_item== other.other_item
def __ne__(self, other):
returnself.other_item!= other.other_item
c = Bar(5)
a == c #抛出AttributeError:'Foo'对象没有属性'other_item'进行检查isinstance()或类似操作将有助于防止这种情况(如果需要)。