Python中自定義類未定義__lt__方法使用sort/sorted排序會怎么處理?

《第8.23節(jié) Python中使用sort/sorted排序與“富比較”方法的關系分析》中介紹了排序方法sort和函數(shù)sorted在沒有提供key參數(shù)的情況下默認調(diào)用lt方法來進行排序比較,如果類中沒有定義lt方法Python會怎么處理?
我們直接看案例:
一、 案例說明
本文案例直接在《第8.23節(jié) 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參數(shù)的情況下Python排序方法調(diào)用了gt方法,并按gt方法比較大小的模式實現(xiàn)了數(shù)據(jù)排序,其實這與《Python的富比較方法lt、gt之間的關聯(lián)關系分析》是一致的。
最后,如果gt方法也沒有定義會怎么樣?在此就不深入介紹,根據(jù)老猿的驗證,如果ltgt方法都沒定義,其他富比較方法實現(xiàn)了,Python無法執(zhí)行排序操作,會報異常:TypeError: '<' not supported between instances of XX and XX。

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

請大家多多支持,點贊、評論和加關注!謝謝!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容