实现类的比较操作
类之间的实例可以用<,<=,>,>=,==,!=的运算符进行比较。可以对比较运算符重载,实现__lt__,__le,__gt__,__ge__,__eq__,__ne__这些方式。全部使用以上方法,会很复杂和多余。这里使用了functools库中的total_ordering装饰器简化代码。例如下:代码是实现了矩形与圆形面积的比较
from abc import abstractmethod from functools import total_ordering from math import pi @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 Cirle(Shape): def __init__(self, r): self.r = r def area(self): return self.r ** 2 * pi r = Rectangle(4, 5) c = Cirle(2) '''对矩形面积与圆形面积的比较''' print r < c print '-'*20 print r <= c print '-'*20 print r == c print '-'*20 print r >= c print '-'*20 print r > c
运行结果: