python如何让类支持比较运算


Posted in Python onMarch 20, 2018

本文实例为大家分享了python类支持比较运算的具体代码,供大家参考,具体内容如下

案例:

有时我们希望自定义的类,实例间可以使用比较运算符进行比较,我们自定义比较的行为。

需求:

有一个矩形的类,我们希望比较两个矩形的实例时,比较的是他们的面积

如何解决这个问题?

在类中重新定义比较运算符,所有的比较运算可以简化为两个基本的比较运算,小于和等于比较

单个类比较

#!/usr/bin/python3
 
from math import pi
 
 
class Circle(object):
  def __init__(self, radius):
    self.radius = radius
 
  def get_area(self):
    return round(pow(self.radius, 2) * pi, 2)
 
  # 重定义小于比较
  def __lt__(self, other):
    return self.get_area() < other.get_area()
 
  # 重定义等于比较
  def __eq__(self, other):
    return self.get_area() == other.get_area()
 
if __name__ == '__main__':
  c1 = Circle(3.0)
  c2 = Circle(5.0)
 
  print(c1 < c2)   # c1.__le__(c2)
  print(c1 == c2)   # c1.__eq__(c2)

两个类比较

#!/usr/bin/python3
 
from math import pi
 
 
class Circle(object):
  def __init__(self, radius):
    self.radius = radius
 
  def get_area(self):
    return round(pow(self.radius, 2) * pi, 2)
 
  # 重定义小于比较
  def __lt__(self, other):
    return self.get_area() < other.get_area()
 
  # 重定义等于比较
  def __eq__(self, other):
    return self.get_area() == other.get_area()
 
if __name__ == '__main__':
  c1 = Circle(3.0)
  c2 = Circle(5.0)
 
  print(c1 < c2)   # c1.__le__(c2)
  print(c1 == c2)   # c1.__eq__(c2)
 
 
# !/usr/bin/python3
 
from math import pi
 
 
class Circle(object):
  def __init__(self, radius):
    self.radius = radius
 
  def get_area(self):
    return round(pow(self.radius, 2) * pi, 2)
 
  # 重定义小于比较
  def __lt__(self, other):
    return self.get_area() < other.get_area()
 
  # 重定义等于比较
  def __eq__(self, other):
    return self.get_area() == other.get_area()
 
 
class Rectangle(object):
  def __init__(self, width, height):
    self.width = width
    self.height = height
 
  def get_area(self):
    return self.width * self.height
 
  # 重定义小于比较
  def __lt__(self, other):
    return self.get_area() < other.get_area()
 
  # 重定义等于比较
  def __eq__(self, other):
    return self.get_area() == other.get_area()
 
 
if __name__ == '__main__':
  c1 = Circle(5.0)
  R1 = Rectangle(4.0, 5.0)
 
  print(c1 > R1) # c1.__le__(c2)
  print(c1 == R1) # c1.__eq__(c2) 

会出现一个问题,重复代码,如何解决?

通过functools下类的装饰器total_ordering进行比较

# !/usr/bin/python3
 
from math import pi
from abc import abstractmethod
from functools import total_ordering
 
 
@total_ordering
class Shape(object):
  """
  定义一个抽象类,重定义比较运算,再定义抽象方法,然后子类通过这个方法进行比较,
  其他子类比较类都需要重构抽象方法,实现比较运算
  """
   
  # 标记比较方法,抽象方法
  @abstractmethod
  def get_area(self):
    pass
   
  # 重定义小于比较
  def __lt__(self, other):
    return self.get_area() < other.get_area()
   
  # 重定义等于比较
  def __eq__(self, other):
    return self.get_area() == other.get_area()
 
 
class Circle(Shape):
  def __init__(self, radius):
    self.radius = radius
   
  def get_area(self):
    return round(pow(self.radius, 2) * pi, 2)
   
 
class Rectangle(Shape):
  def __init__(self, width, height):
    self.width = width
    self.height = height
   
  def get_area(self):
    return self.width * self.height
 
 
if __name__ == '__main__':
  c1 = Circle(5.0)
  R1 = Rectangle(4.0, 5.0)
   
  print(c1 > R1) # c1.__le__(c2)
  print(c1 == R1) # c1.__eq__(c2)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
跟老齐学Python之做一个小游戏
Sep 28 Python
Python中统计函数运行耗时的方法
May 05 Python
Python对列表中的各项进行关联详解
Aug 15 Python
Python实现的矩阵类实例
Aug 22 Python
Mac中Python 3环境下安装scrapy的方法教程
Oct 26 Python
Django 使用Ajax进行前后台交互的示例讲解
May 28 Python
Python玩转加密的技巧【推荐】
May 13 Python
解决安装pyqt5之后无法打开spyder的问题
Dec 13 Python
python实现坦克大战
Apr 24 Python
python3+openCV 获取图片中文本区域的最小外接矩形实例
Jun 02 Python
pyCharm 设置调试输出窗口中文显示方式(字符码转换)
Jun 09 Python
Python趣味实战之手把手教你实现举牌小人生成器
Jun 07 Python
python如何为创建大量实例节省内存
Mar 20 #Python
python如何对实例属性进行类型检查
Mar 20 #Python
python如何在循环引用中管理内存
Mar 20 #Python
Windows 7下Python Web环境搭建图文教程
Mar 20 #Python
Python中%是什么意思?python中百分号如何使用?
Mar 20 #Python
Python实现类似比特币的加密货币区块链的创建与交易实例
Mar 20 #Python
Django开发中复选框用法示例
Mar 20 #Python
You might like
PHP中CheckBox多选框上传失败的代码写法
2017/02/13 PHP
laravel-admin表单提交隐藏一些数据,回调时获取数据的方法
2019/10/08 PHP
php下的原生ajax请求用法实例分析
2020/02/28 PHP
javascript 图片上一张下一张链接效果代码
2010/03/12 Javascript
学习面向对象之面向对象的术语
2010/11/30 Javascript
js列举css中所有图标的实现代码
2011/07/04 Javascript
js获取本机的外网/广域网ip地址完整源码
2013/08/12 Javascript
如何解决谷歌浏览器下jquery无法获取图片的尺寸
2015/09/10 Javascript
jQuery实现下拉框左右移动(全部移动,已选移动)
2016/04/15 Javascript
JQuery为元素添加样式的实现方法
2016/07/20 Javascript
利用jQuery对无序列表排序的简单方法
2016/10/16 Javascript
JS+HTML5实现的前端购物车功能插件实例【附demo源码下载】
2016/10/17 Javascript
JavaScript输入框字数实时统计更新
2017/06/17 Javascript
vue.js实例todoList项目
2017/07/07 Javascript
详解nuxt路由鉴权(express模板)
2018/11/21 Javascript
关于vue组件事件属性穿透详解
2019/10/28 Javascript
vue新建项目并配置标准路由过程解析
2019/12/09 Javascript
vue props 一次传多个值实例
2020/07/22 Javascript
Element DateTimePicker日期时间选择器的使用示例
2020/07/27 Javascript
Vue实现多页签组件
2021/01/14 Vue.js
python实现的登陆Discuz!论坛通用代码分享
2014/07/11 Python
用python读写excel的方法
2014/11/18 Python
python实现文件路径和url相互转换的方法
2015/07/06 Python
使用Python计算玩彩票赢钱概率
2019/06/26 Python
使用Pandas对数据进行筛选和排序的实现
2019/07/29 Python
解决django后台管理界面添加中文内容乱码问题
2019/11/15 Python
Python urlopen()和urlretrieve()用法解析
2020/01/07 Python
Django自关联实现多级联动查询实例
2020/05/19 Python
Html5新标签datalist实现输入框与后台数据库数据的动态匹配
2017/05/18 HTML / CSS
诗狄娜化妆品官方网站:Stila Cosmetics
2016/12/21 全球购物
美国最大的家庭鞋类零售商之一:Shoe Carnival
2017/10/06 全球购物
OSPREY LONDON官网:英国本土皮具品牌
2019/05/31 全球购物
银行见习期自我鉴定
2014/01/29 职场文书
市场部业务员岗位职责
2014/04/02 职场文书
2015届大学生就业推荐表自我评价
2014/09/27 职场文书
25张裸眼3D图片,带你重温童年的记忆,感受3D的魅力
2022/02/06 杂记