首页 > 其他 > 详细

实现类的比较操作

时间:2017-04-13 17:00:46      阅读:196      评论:0      收藏:0      [点我收藏+]

类之间的实例可以用<,<=,>,>=,==,!=的运算符进行比较。可以对比较运算符重载,实现__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

运行结果:

技术分享

 

实现类的比较操作

原文:http://www.cnblogs.com/misslin/p/6704424.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!