让类支持比较操作

方法1:比较运算符重载,需要实现以下方法:小于,小于等于,大于,大于等于,等于,不等于。

from functools import total_ordering
from abc import ABCMeta,abstractmethod

@total_ordering  #装饰类
class Shape(object):   #父类
    @abstractmethod
    def area(self):
        pass
    # 小于
    def __lt__(self, other):
        print('in_lt_')
        if not isinstance(other, Shape):
            raise TypeError('other is not Shape')
        return self.area() < other.area()

    def __eq__(self, other):
        print('in_eq_')
        if not isinstance(other, Shape):
            raise TypeError('other is not Shape')
        return self.area() == other.area()

class Rectangle(Shape):           #继承
    def __init__(self, w, h):
        self.w = w
        self.h = h
    def area(self):
        return self.w * self.h

class Circle(Shape):
    def __init__(self, r):
        self.r = r
    def area(self):
        return self.r ** 2 * 3.14
r1 = Rectangle(5, 3)
r2 = Rectangle(4, 4)
c1 = Circle(3)

print(c1 <= r1)
print(r1 > c1)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值