• 实现类的比较操作


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

    运行结果:

  • 相关阅读:
    计蒜客 移除数组中的重复元素 (双指针扫描)
    计蒜客 寻找插入位置 (二分查找)
    poj 1007 DNA Sorting
    全排列函数 nyoj 366(next_permutation()函数)
    nyoj 202 红黑树
    nyoj 92 图像有用区域
    nyoj 82 迷宫寻宝(一)
    nyoj 58 最少步数
    nyoj 43 24 Point game
    nyoj 42 一笔画问题
  • 原文地址:https://www.cnblogs.com/misslin/p/6704424.html
Copyright © 2020-2023  润新知