Python 如何让类支持比较操作

Jackey Python 1,916 次浏览 没有评论
# 如何让类支持比较操作
from functools import total_ordering
from abc import ABCMeta, abstractmethod


@total_ordering
class Shape(object):
    @abstractmethod
    def area(self):
        pass

    # 小于
    def __lt__(self, obj):
        if not isinstance(obj, Shape):
            raise TypeError('obj is not shape')
        return self.area() < obj.area()

    # 小于等于
    # def __le__(self, obj):
    #     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()

    # 大于
    def __gt__(self, obj):
        if not isinstance(obj, Shape):
            raise TypeError('obj is not shape')
        return self.area() > obj.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(r1 <= c1)  # r1.__lt__(r2)
print(r1 > c1)

 

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

Go