zoukankan      html  css  js  c++  java
  • 实现类的比较操作

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

    运行结果:

  • 相关阅读:
    nginx入门
    nginx负载均衡算法
    Nginx+Tomcat搭建高性能负载均衡集群
    简单搭建dubbo
    webservice和restful的区别
    webservice、httpClient、dubbo的区别
    sublime 插件
    【exam answer 1】
    给定一个 1-100 的整数数组,请找到其中缺少的数字。
    Hibernate中clear()、evict()、flush()的方法使用说明
  • 原文地址:https://www.cnblogs.com/misslin/p/6704424.html
Copyright © 2011-2022 走看看