2021-03-15 类的比较

逻辑教育.png

题目要求:建立两个求面积的类,通过实例对象比较面积的大小

from math import pi
from functools import total_ordering
import abc

#抽象基类装饰器
@total_ordering
class Shape(metaclass=abc.ABCMeta):

    @abc.abstractmethod
    def area(self):
        pass

    def __gt__(self, other):
        return self.area() > other.area()

    def __eq__(self, other):
        return self.area() == other.area()


class Rect(Shape):
    def __init__(self, w, h):
        self.w = w
        self.h = h

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

    def __str__(self):
        return f"{self.area()}"


class Circle(Shape):
    def __init__(self, r):
        self.r = r

    def area(self):
        return self.r ** 2 * pi

    def __str__(self):
        return f"{self.area()}"


r = Rect(2, 3)
c = Circle(2)
print("Rect:", r)
print("Circle:", c)
print(r < c)
  • 运行结果:
Rect: 6
Circle: 12.566370614359172
True

你可能感兴趣的:(2021-03-15 类的比较)