from functools import total_ordering
from abc import ABCMeta, abstractclassmethod
@total_ordering
class Shape(metaclass=ABCMeta): #子类都要实现比较,定义抽象基类
@abstractclassmethod #子类必须实现抽象方法才可以使用
def area(self):
pass
# 使用total_ordering装饰器可以简化类的比较操作
# > < <= >= = !=只要实现 = 和任意其中一个,即可使用全部比较方法
# 具体的实现逻辑是, a>b --> true not (b>a) --> true
def __lt__(self, obj):
print('__lt__', self, obj)
return self.area() < obj.area()
def __eq__(self, obj):
return self.area() == obj.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 'Rect:(%s, %s)' % (self.w, self.h)
import math
class Circle(Shape):
def __init__(self, r):
self.r = r
def area(self):
return self.r ** 2 * math.pi
rect1 = Rect(6, 9) # 54
rect2 = Rect(7, 8) # 56
c = Circle(8)
print(rect1 < c)
print(c > rect2)
【python】比较运算符重载,以及抽象基类
猜你喜欢
转载自blog.csdn.net/qq_38065133/article/details/82317229
今日推荐
周排行