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()或类似操作将有助于防止这种情况(如果需要)。
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下