python3 50个练习例子之让类支持比较操作

本文通过50个实例讲解了如何在Python3中让类支持比较操作,包括使用functools.total_ordering类装饰器进行相同类型比较,以及通过定义抽象方法和继承实现不同类型的比较操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 比较操作
1. <   对应 __lt__
2. <= 对应 __le__
3. >  对应 __gt__
4. >=  对应 __ge__
5. ==  对应 __eq__
6. !=  对应 __ne__

  1. 相同类型的比较
class Rectangle(object):
    def __init__(self,w,h):
        self.w = w
        self.h = h

    def area(self):
        return self.w * self.h

    # <
    def __lt__(self,obj):
        print('__lt__') # 打印,说明进来
        # 对类型进行检查
        if not isinstance(obj,Rectangle):
            raise TypeError('obj is not Rectangle')
        return self.area() < obj.area()

    # <=
    def __le__(self,obj):
  		# 对类型进行检查
        if not isinstance(obj,Rectangle):
            raise TypeError('obj is not Rectangle')
        return self.area() <= obj.area()

    # >
    def __gt__(self,obj):
    	# 对类型进行检查
        if not isinstance(obj,Rectangle):
            raise TypeError('obj is not Rectangle')
        return self.area() > obj.area()

    # >=
    def __ge__(self,obj):
   		# 对类型进行检查
        if not isinstance(obj,Rectangle):
            raise TypeError('obj is not Rectangle')
        return self.area() >= obj.area()
    
    # ==
    def __eq__(self,obj):
    	# 对类型进行检查
        if not isinstance(obj,Rectangle):
            raise TypeError('obj is not Rectangle')
        return self.area() == obj.area()

    # !=
    def __ne__(self,obj):
    	# 对类型进行检查
        if not isinstance(obj,Rectangle):
            raise TypeError('obj is not Rectangle')
        return self.area() != obj.area()

r1 = Rectangle(3,3)
r2 = Rectangle(4,4)
r3 = Rectangle(4,4)

print(r1 < r2) # True
print(r1 <= r2) # True
print(r1 > r2) # False
print(r1 >= r2) # False
print(r2 == r3) # True
print(r2 != r3) # False

s = 16
print(r2 == s) # TypeError: obj is not Rectangle

  1. 相同类型的比较操作(functools.total_ordering,类装饰器)
from functools import total_ordering

@total_ordering
class Rectangle(object):
    def __init__(self,w,h):
        self.w = w
        self.h = h

    def area(self):
        return self.w * self.h

    # <
    def __lt__(self,obj):
        print('__lt__') # 总共被调用4次  < ,<= ,> ,>=
        # 对类型进行检查
        if not isinstance(obj,Rectangle):
            raise TypeError('obj is not Rectangle')
        return self.area() < obj.area()

     # ==
    def __eq__(self,obj):
    	# 对类型进行检查
        if not isinstance(obj,Rectangle):
            raise TypeError('obj is not Rectangle')
        return self.area() == obj.area()
""''
用functools.total_ordering模块的方法,只需要实现<,==即可
<=  对应 < or ==
> 对应 not(< or ==)
>= 对应 not <
!= 对应 not ==
"""


r1 = Rectangle(3,3)
r2 = Rectangle(4,4)
r3 = Rectangle(4,4)

print(r1 < r2) # True
print(r1 <= r2) # True
print(r1 > r2) # False
print(r1 >= r2) # False
print(r2 == r3) # True
print(r2 != r3) # False

s = 16
print(r2 == s) # TypeError: obj is not Rectangle
  1. 不同类型的比较操作(写抽象方法,继承)
import math
from functools import total_ordering
from abc import abstractmethod

@total_ordering
class Shape(object):
	# 写抽象方法
    @abstractmethod
    def area(self):
        pass # 什么也不做
    
    # <
    def __lt__(self,obj):
        print('__lt__') # 总共被调用4次  < ,<= ,> ,>=
        # 对类型进行检查
        if not isinstance(obj,Shape):
            raise TypeError('obj is not Shape')
        return self.area() < obj.area()

     # ==
    def __eq__(self,obj):
    	# 对类型进行检查
        if not isinstance(obj,Shape):
            raise TypeError('obj is not Shape')
        return self.area() == obj.area()
    
# 继承Shape
class Rectangle(Shape):
    def __init__(self,w,h):
        self.w = w
        self.h = h

     # 实现area
    def area(self):
        return self.w * self.h

# 继承Shape
class Circle(Shape):
    def __init__(self,radius):
        self.radius = radius

    # 实现area
    def area(self):
        return self.radius * 2 * math.pi

   
r1 = Rectangle(4,4)
r2 = Rectangle(4,4)
r3 = Circle(4)

print(r2 < r3) # True
print(r2 <= r3) # True
print(r2 > r3) # False
print(r2 >= r3) # False
print(r1 == r2) # True
print(r1 != r2) # False

s = 16
print(r2 == s) # TypeError: obj is not Shape
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值