一.__eq__方法

在我们定义一个类的时候,常常想对一个类所实例化出来的两个对象进行判断这两个对象是否是完全相同的。一般情况下,我们认为如果同一个类实例化出来的两个对象的属性全都是一样的话,那么这两个对象是相同的。但是如果我们直接用"==”来判断这两个对象知否相等,那么结果一定是不相等的,因为这两个对象的地址一定不同,它们在内存当中的不同区域,比如我们有代码:

class Item:

def __init__(self, name, weight):

self.name=name

self.weight=weight

cat_1 = Item('Cat', 5)

cat_2 = Item('Cat', 5)

print(cat_1 == cat_2)

这段代码当中,我们创建了两个“item”对象,它们的属性“name”和“weight”都完全一致,这段程序看似正确,应该打印出True,但实际上输出是:

False

原因则是因为这两个对象的地址是不同的,那么怎么才能够让它们只要属性相同两个对象就相等呢?那就是利用__eq__方法来进行判断,这个方法默认有两个参数,一个是self,另一个是other.也就是用自身的属性和other对象的属性分别进行比较,如果比对成功则返回True,失败则返回False。你也可以自定义想要比较的属性有哪些,也不一定是全部的属性都一样才相等。我们有代码:

class Item:

def __init__(self, name, weight):

self.name=name

self.weight=weight

def __eq__(self, other):

# `__eq__` is an instance method, which also accepts

# one other object as an argument.

if type(other)==type(self) and other.name==self.name and other.weight==self.weight:

return True

else:

return False# 返回False这一步也是需要写的哈,不然判断失败就没有返回值了

cat_1 = Item('Cat', 5)

cat_2 = Item('Cat', 5)

print(cat_1.__eq__(cat_2)) # should evaluate to True

print(cat_1 == cat_2) # should also evaluate to True

这样,就会打印出两个True了。

二.__str__方法

我们如果把自己创建的对象直接打印出来,那么一般是这样,比如我们有代码:

print(cat_1)

输出:

<__main__.item object at>

这是一个看起来十分难看的输出,输出的是这对象的类别和地址。但我们可以把这个输出改成自己想要的样子,那就是利用__str__方法。我们重写这个方法,让这个返回一个值,那么最后输出的就是我们的返回值,如下所示:

class Item:
def __init__(self, name, weight):
self.name=name
self.weight=weight
def __eq__(self, other):
if type(other)==type(self) and other.name==self.name and other.weight==self.weight:
return True
else:
return False
def __str__(self):
return 'the name of this cat is {}'.format(self.name)
再次创建并打印:
cat_1 = Item('Cat', 5)
cat_2 = Item('Cat', 5)
print(cat_1)
print(cat_2)
可得到输出:
the name of this cat is Cat
the name of this cat is Cat

这样这个输出看起来就不会有那么麻烦了,自定义的输出果然清晰了不少啊!