第8.23节 Python中使用sort/sorted排序与“富比较”方法的关系分析
2023-09-27 14:26:59 时间
一、 引言
《第8.21节 Python中__lt__、gt__等 “富比较”(“rich comparison”)方法用途探究》和《第8.22节 Python案例详解:重写 “富比较”方法控制比较逻辑》介绍了富比较方法及执行比较操作与富比较的对应关系,本节将通过案例分析排序操作与富比较方法的对应关系。
二、 案例说明
复用上节定义的类Car(如果你没看上节可以忽略这个背景,因为代码是完整的),包括实例属性和实例方法都保持不变,我们来(这4个方法的用途请见上一节《第8.21节 Python中__lt、__gt__等 “富比较”(“rich comparison”)方法用途探究》,然后我们定义多个实例变量放到一个列表中来进行排序,看执行效果。
为了分析,我们定义多个实例变量放到一个列表中,调用列表的排序方法sort来对列表进行排序,当然也可以调用sorted函数进行排序,二者大部分功能是一样的,但略有区别,在此就不展开讲了,老猿考虑开单章专门介绍。
三、 代码
>>> class Car():
def __init__(self,carname,oilcper100km, price):
self.carname,self.oilcper100km,self.price = carname,oilcper100km, price
def __lt__(self,other):
print("execute __lt__")
return self.price<other.price
def __le__(self,other):
print("execute __le__")
return self.price>other.price
def __gt__(self,other):
print("execute __gt__")
return self.oilcper100km>other.oilcper100km
def __ge__(self,other):
print("execute __ge__")
return self.oilcper100km<other.oilcper100km
def __repr__(self):
#return f"('{self.carname}',{self.oilcper100km},{self.price})"
return str(self.__dict__)
>>> car1,car2,car3 = Car('爱丽舍',8,10),Car('凯美瑞',7,27),Car('科帕奇',12,23)
>>> cars=[car1,car2,car3]
>>> cars
[{'carname': '爱丽舍', 'oilcper100km': 8, 'price': 10}, {'carname': '凯美瑞', 'oilcper100km': 7, 'price': 27}, {'carname': '科帕奇', 'oilcper100km': 12, 'price': 23}]
>>> cars.sort()
execute __lt__
execute __lt__
execute __lt__
execute __lt__
>>> cars
[{'carname': '爱丽舍', 'oilcper100km': 8, 'price': 10}, {'carname': '科帕奇', 'oilcper100km': 12, 'price': 23}, {'carname': '凯美瑞', 'oilcper100km': 7, 'price': 27}]
>>>
四、 案例截屏
五、 案例分析
- sort排序时执行了四次__lt__方法调用,没有执行其他富比较方法,因此sort排序默认调用的富比较方法是__lt__方法;
- sort排序时改变了cars中的元素顺序,确保了列表中的元素是按__lt__方法指定的排序属性price进行排序的;
- 本节的__repr__方法实现代码与上节有所不同,这个应该是__repr__方法快速实现的一种方案,且符合Python对__repr__方法的要求。
本节参考资料:
1、《第8.21节 Python中__lt__、__gt__等 “富比较”(“rich comparison”)方法用途探究》;
2、《第8.15节 Python重写自定义类的__repr__方法》
老猿Python,跟老猿学Python!
博客地址:https://blog.csdn.net/LaoYuanPython
请大家多多支持,点赞、评论和加关注!谢谢!
相关文章
- 支付宝扫“福”字活动马上开始,看我如何使用python制作一个“福”字吧
- Python入门:ChainMap 有效管理多个上下文
- 微电网两阶段鲁棒优化经济调度方法(Python代码实现)
- 【Python—字典的用法】创建字典的3种方法
- python 高级篇-面向对象-6 多继承
- 【2023最全教程】Python接口测试实战之搭建自动化测试框架(建议收藏)
- 【6】python生成数据曲线平滑处理——(Savitzky-Golay 滤波器、convolve滑动平均滤波)方法介绍,推荐玩强化学习的小伙伴收藏
- Python +Mysql 安装部署
- python小练习10 -- 顺序栈和链栈的实现及其应用
- PyQt(Python+Qt)学习随笔:QMainWindow的addDockWidget方法增加QDockWidget停靠窗到主窗口
- PyQt(Python+Qt)学习随笔:QTreeWidgetItem项列图标的访问方法
- Python中自定义类未定义__lt__方法使用sort/sorted排序会怎么处理?
- Python中排序函数sorted和排序方法sort的异同点对比分析
- 第8.23节 Python中使用sort/sorted排序与“富比较”方法的关系分析
- Python的富比较方法__eq__和__ne__之间的关联关系分析
- 使用python写appium用例
- Python 安装pandas报错:ValueError: check_hostname requires server_hostname解决方法
- Python 使用Lambda对list(列表)中指定格式字符串元素排序方法
- Python 通过两个字符串(分隔符)分割拆(split)分字符串的方法代码总结
- Python numpy.full函数方法的使用
- python遍历数组的方法小结
- python遇到Segmentation fault (core dumped)调试方法
- C++调用python方法及环境配置(Windows环境、VS工具)
- python中PIL.Image和opencv处理图像方法及区别
- python - python中的super()方法 (代码详解)