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 送给学长毕业祝福语简短