方法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)