Python中自定义类未定义__lt__方法使用sort/sorted排序会怎么处理?

《第8.23节 Python中使用sort/sorted排序与“富比较”方法的关系分析》中介绍了排序方法sort和函数sorted在没有提供key参数的情况下默认调用__lt__方法来进行排序比较,如果类中没有定义__lt__方法Python会怎么处理?
我们直接看案例:
一、 案例说明
本文案例直接在《第8.23节 Python中使用sort/sorted排序与“富比较”方法的关系分析》基础上通过两个三引号注释掉__lt__方法的定义,然后定义实例列表进行排序。
二、 案例代码

>>> 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.sort()
execute __gt__
execute __gt__
execute __gt__
>>> cars
[{'carname': '凯美瑞', 'oilcper100km': 7, 'price': 27}, {'carname': '爱丽舍', 'oilcper100km': 8, 'price': 10}, {'carname': '科帕奇', 'oilcper100km': 12, 'price': 23}]
>>>

三、 案例截图
在这里插入图片描述
四、 案例分析
从上述案例可以看到,注释掉__lt__方法后,在未指定key参数的情况下Python排序方法调用了__gt__方法,并按__gt__方法比较大小的模式实现了数据排序,其实这与《Python的富比较方法__lt__、__gt__之间的关联关系分析》是一致的。
最后,如果__gt__方法也没有定义会怎么样?在此就不深入介绍,根据老猿的验证,如果__lt__和__gt__方法都没定义,其他富比较方法实现了,Python无法执行排序操作,会报异常:TypeError: ‘<’ not supported between instances of XX and XX。

老猿Python,跟老猿学Python!
博客地址:https://blog.csdn.net/LaoYuanPython

请大家多多支持,点赞、评论和加关注!谢谢!

原文地址:https://www.cnblogs.com/LaoYuanPython/p/11932087.html