python 如何让类支持比较操作

如何让类支持比较操作

如果我们定义矩形类,圆的类的话,那就避免不了要实现计算面积的方法,然而当我们想要通过实例对象比较它们面积的大小时(>,<,>=,<=,==,!=),应该怎么实现?

  • 在python里,__le__对应的是<=,__ge__对应的是大于等于,__lt__对应的是小于······以此类推

total_ordering的使用

我们可以使用functools模块里的一个total_ordering装饰器就可以实现实例之间大小的比较

  • 示例代码
    import math
    from functools import total_ordering
    
    
    @total_ordering
    class Circle(object):
        def __init__(self, redius):
            self.redius = redius
    
        def area(self):
            return math.pi * self.redius ** 2
        "只需要定义一种比较的方法就够了"
        def __le__(self, other):
            return self.area() <= other.area()
    
    
    c1 = Circle(3)
    c2 = Circle(5)
    print(c1 > c2)
    
    

最后,有喜欢博主写的内容的伙伴可以收藏加关注哦!

猜你喜欢

转载自blog.csdn.net/weixin_44604586/article/details/106833950