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()或类似操作将有助于防止这种情况(如果需要)。
热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短