第8.22节 Python案例详解:重写 “富比较”方法控制比较逻辑

一、 案例说明
本节定义一个小汽车的类Car,类中包括车名carname、百公里油耗oilcostper100km、价格price三个属性。然后实现__lt__、__gt__、__le__、__ge__四个方法(这4个方法的用途请见上一节《第8.21节 Python中__lt__、__gt__等 “富比较”(“rich comparison”)方法用途探究》(https://blog.csdn.net/LaoYuanPython/article/details/95042104),为了说明问题,我们将__lt__与__le__的比较逻辑以及__gt__与__ge__的比较逻辑故意弄成了相反,同时重写了__repr__方法以输出格式化的详细信息。然后我们定义两个实例变量来进行大小比较,看执行效果。
二、 案例代码

>>> class Car():
   def __init__(self,carname,oilcostper100km, price):
       self.carname,self.oilcostper100km,self.price = carname,oilcostper100km, 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.oilcostper100km>other.oilcostper100km

   def __ge__(self,other):
       print("execute __ge__")
       return self.oilcostper100km<other.oilcostper100km

   def __repr__(self):  #重写__repr__方法输出repr信息
       return  f"('{self.carname}',{self.oilcostper100km},{self.price})"

>>> car1,car2 = Car('爱丽舍',8,10),Car('凯美瑞',7,27)
>>> car1<car2,car1<=car2,car1>car2,car1>=car2
execute __lt__
execute __le__
execute __gt__
execute __ge__
(True, False, True, False)
>>>

三、 案例截屏 在这里插入图片描述
四、 案例分析

  1. 通过4个比较的输出信息可以得知,<、<=、>、>=分别调用了__lt__、__le__、__gt__、__ge__四个方法;
  2. 由于__lt__、__le__使用price进行比较,且真正的比较表达式是相反的两个逻辑,所以二者输出结果也完全相反,同理__gt__、__ge__也是一样,这说明Python自定义类的实例对象比较大小时,对象的大小判断规则是由开发者自己定义的,并没有要求“小于等于”就一定要包含“小于”,二者之间在实现时没有逻辑关系,__gt__与__ge__也如此,同理__gt__与__lt__也无需是相反的结果,最终的逻辑应该根据业务需要进行重写确认;
  3. 通过以上案例,我们也知道,通过重写富比较方法,我们完全可以截获对象比较逻辑的调用;
  4. 实际的富比较方法还有__eq__和__ne__,这两个方法object类实现了,可以直接继承使用,但也可以重写。

本节参考资料:
1、《第8.21节 Python中__lt__、__gt__等 “富比较”(“rich comparison”)方法用途探究》
2、《第8.15节 Python重写自定义类的__repr__方法》

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

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

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