python(Class5)

2016-09-11  本文已影响17人  OldSix1987

让类支持比较操作


类似运算符重载



from functools import total_ordering
from abc import ABCMeta, abstractclassmethod


@total_ordering  # 装饰器,作用类似于c++中的模版:根据小于和等于的方法重载,可以自行推测出小于等于和大于和大于等于的方法定义,大大的简化了代码
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)

上一篇 下一篇

猜你喜欢

热点阅读