网站首页 > 基础教程 正文
python中默认是可以对数值类型进行比较大小的,那我们自定义的对象怎么支持比较大小呢?
如果我们要对自定义对象增加比较大小的功能,只需要实现6个比较相关的方法即可:__lt__、__le__、__eq__、__ne__、__gt__、__ge__
我们以长方形面积类为例来说明怎么使用,如下代码定义长方形面积类:
class RectArea:
def __init__(self, width, height):
self.width = width
self.height = height
self.area = width * height
如果我们像下面这样直接比较大小,会抛出不支持比较操作的异常:
s1 = RectArea(1, 2)
s2 = RectArea(2, 3)
print(s1 > s2)
那我们怎么让它支持比较操作呢?很简单,实现上面提到的6个操作方法即可,如下代码:
from random import randint
class RectArea:
def __init__(self, width, height):
self.width = width
self.height = height
self.area = width * height
def __lt__(self, other):
return self.area < other.area
def __le__(self, other):
return self.area <= other.area
def __eq__(self, other):
return self.area == other.area
def __ne__(self, other):
return self.area != other.area
def __gt__(self, other):
return self.area > other.area
def __ge__(self, other):
return self.area >= other.area
def __repr__(self):
return f"{self.area}"
rects = []
for width, height in zip((randint(1, 1000) for _ in range(10)), (randint(1, 1000) for _ in range(10))):
rects.append(RectArea(width, height))
rects.sort()
print(rects)
这样就能用于比较大小和排序操作了。
- 上一篇: Python应用——自定义排序全套方案
- 下一篇: Python实现快速排序
猜你喜欢
- 2024-11-22 Python 实现经典算法之堆排序
- 2024-11-22 Python版排序算法总结
- 2024-11-22 python冷门操作-11.list排序干货
- 2024-11-22 Python 排序了解一下
- 2024-11-22 Python实现冒泡排序
- 2024-11-22 Python 快速排序:高效算法一探究竟
- 2024-11-22 Python实现快速排序
- 2024-11-22 Python应用——自定义排序全套方案
- 2024-11-22 Python函数知识整理
- 2024-11-22 冒泡排序(python版)
- 最近发表
- 标签列表
-
- jsp (69)
- gitpush (78)
- gitreset (66)
- python字典 (67)
- dockercp (63)
- gitclone命令 (63)
- dockersave (62)
- linux命令大全 (65)
- pythonif (86)
- location.href (69)
- dockerexec (65)
- tail-f (79)
- queryselectorall (63)
- location.search (79)
- bootstrap教程 (74)
- deletesql (62)
- linuxgzip (68)
- 字符串连接 (73)
- html标签 (69)
- c++初始化列表 (64)
- mysqlinnodbmyisam区别 (63)
- arraylistadd (66)
- mysqldatesub函数 (63)
- window10java环境变量设置 (66)
- c++虚函数和纯虚函数的区别 (66)