讓類支持比較操作
類似運算符重載
from functools import total_ordering
from abc import ABCMeta, abstractclassmethod
@total_ordering # 裝飾器,作用類似于c++中的模版:根據(jù)小于和等于的方法重載,可以自行推測出小于等于和大于和大于等于的方法定義,大大的簡化了代碼
class Shape(object):
@abstractclassmethod # 抽象基類,子類必須覆蓋
def area(self):
pass
def __lt__(self, other):
if not isinstance(other, Shape):
raise TypeError('obj is Not Shape')
return self.area() < other.area()
def __eq__(self, other):
if not isinstance(other, Shape):
raise TypeError('obj 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
c1 = Circle(3)
r1 = Rectangle(5, 3)
r2 = Rectangle(4, 4)
print(r1 <= r2)
print(r1 > c1)
# print(r1 > 1)