Python:__eq__和__str__函数的使用示例
作者:Geeksongs 时间:2023-01-12 02:45:31
一.__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 0x7f8e3d99f190
这是一个看起来十分难看的输出,输出的是这对象的类别和地址。但我们可以把这个输出改成自己想要的样子,那就是利用__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
这样这个输出看起来就不会有那么麻烦了,自定义的输出果然清晰了不少啊!
来源:https://www.cnblogs.com/geeksongs/p/13053987.html
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
深入理解 Python 中的多线程 新手必看
Python数据库反向生成Model最优方案示例
Python调用C++程序的方法详解
python使用7z解压软件备份文件脚本分享
python实现动态数组的示例代码
图片格式与设计那点事儿
![](https://img.aspxhome.com/file/UploadPic/20111/6/2-bitmap-88s.jpg)
Mysql使用Describe命令判断字段是否存在
CSS样式表中继承关系的空格与不空格
django从请求到响应的过程深入讲解
![](https://img.aspxhome.com/file/2023/8/72868_0s.png)
python的id()函数介绍
关于python pygame游戏进行声音添加的技巧
Ranorex通过Python将报告发送到邮箱的方法
![](https://img.aspxhome.com/file/2023/4/97654_0s.png)
如何创建支持FILESTREAM的数据库示例探讨
Bootstrap中文本框的宽度变窄并且加入一副验证码图片的实现方法
![](https://img.aspxhome.com/file/2023/3/137013_0s.png)
vue多次循环操作示例
![](https://img.aspxhome.com/file/2023/2/123162_0s.png)
详解Git.gitignore开发必备建议收藏
10款最好的Web开发的 Python 框架
![](https://img.aspxhome.com/file/2023/5/134605_0s.jpg)
CSS解决未知高度的垂直水平居中自适应问题
php+mysqli实现批量替换数据库表前缀的方法
![](https://img.aspxhome.com/file/2023/2/94722_0s.jpg)
对tensorflow中cifar-10文档的Read操作详解
![](https://img.aspxhome.com/file/2023/0/92330_0s.gif)