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 struct.unpack
Sep 06 Python
Python简单获取自身外网IP的方法
Sep 18 Python
django中的HTML控件及参数传递方法
Mar 20 Python
python批量修改文件夹及其子文件夹下的文件内容
Mar 15 Python
python 根据字典的键值进行排序的方法
Jul 24 Python
使用 Django Highcharts 实现数据可视化过程解析
Jul 31 Python
使用python写的opencv实时监测和解析二维码和条形码
Aug 14 Python
Python CSV文件模块的使用案例分析
Dec 21 Python
Python编译为二进制so可执行文件实例
Dec 23 Python
Linux系统下升级pip的完整步骤
Jan 31 Python
如何用Python进行时间序列分解和预测
Mar 01 Python
Python使用pandas导入xlsx格式的excel文件内容操作代码
Dec 24 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
人大复印资料处理程序_查询篇
2006/10/09 PHP
一周让你学会PHP 不错的学习资料
2009/02/06 PHP
php限制上传文件类型并保存上传文件的方法
2015/03/13 PHP
php使用str_shuffle()函数生成随机字符串的方法分析
2017/02/17 PHP
Thinkphp开发--集成极光推送
2017/09/15 PHP
JavaScript高级程序设计 读书笔记之十 本地对象Date日期
2012/02/27 Javascript
Bootstrap入门书籍之(零)Bootstrap简介
2016/02/17 Javascript
JS回调函数简单用法示例
2017/02/09 Javascript
jQuery中的$是什么意思及 $. 和 $().的区别
2018/04/20 jQuery
详解Vue CLI 3.0脚手架如何mock数据
2018/11/23 Javascript
javascript设计模式 ? 代理模式原理与用法实例分析
2020/04/16 Javascript
vue监听浏览器原生返回按钮,进行路由转跳操作
2020/09/09 Javascript
Vue中用JSON实现刷新界面不影响倒计时
2020/10/26 Javascript
javascript实现点击产生随机图形
2021/01/25 Javascript
[01:42]TI4西雅图DOTA2前线报道 第一顿早饭哦
2014/07/08 DOTA
[42:23]完美世界DOTA2联赛PWL S3 Forest vs Rebirth 第二场 12.10
2020/12/13 DOTA
Python编程语言的35个与众不同之处(语言特征和使用技巧)
2014/07/07 Python
python中星号变量的几种特殊用法
2016/09/07 Python
详解Django中间件执行顺序
2018/07/16 Python
对IPython交互模式下的退出方法详解
2019/02/16 Python
15行Python代码实现网易云热门歌单实例教程
2019/03/10 Python
pytorch 自定义参数不更新方式
2020/01/06 Python
Python钉钉报警及Zabbix集成钉钉报警的示例代码
2020/08/17 Python
python 实现简易的记事本
2020/11/30 Python
HTML5 CSS3新的WEB标准和浏览器支持
2009/07/16 HTML / CSS
纽约的奢华内衣店:Journelle
2016/07/29 全球购物
英国第一的滑雪服装和装备零售商:Snow+Rock
2020/02/01 全球购物
将一个数的从第5位开始的7个数取出,其余位置0
2016/05/26 面试题
社区交通安全实施方案
2014/03/22 职场文书
聘用意向书
2014/07/29 职场文书
初中政教处工作总结
2015/08/12 职场文书
2016年秋季运动会加油稿
2015/12/21 职场文书
教师教育心得体会
2016/01/19 职场文书
《颐和园》教学反思
2016/02/19 职场文书
一年之计:2019年下半年的计划
2019/05/07 职场文书
vue+elementui 实现新增和修改共用一个弹框的完整代码
2021/06/08 Vue.js