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 Django模板的使用方法(图文)
Nov 04 Python
Python编写检测数据库SA用户的方法
Jul 11 Python
使用python实现正则匹配检索远端FTP目录下的文件
Mar 25 Python
Python原始字符串与Unicode字符串操作符用法实例分析
Jul 22 Python
urllib和BeautifulSoup爬取维基百科的词条简单实例
Jan 17 Python
Python使用正则表达式获取网页中所需要的信息
Jan 29 Python
如何在python中写hive脚本
Nov 08 Python
Python实现钉钉订阅消息功能
Jan 14 Python
Pycharm激活码激活两种快速方式(附最新激活码和插件)
Mar 12 Python
Python就将所有的英文单词首字母变成大写
Feb 12 Python
ROS系统将python包编译为可执行文件的简单步骤
Jul 25 Python
Python可视化学习之seaborn调色盘
Feb 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
php+redis实现消息队列功能示例
2019/09/19 PHP
记录几个javascript有关的小细节
2007/04/02 Javascript
javascript document.referrer 用法
2009/04/30 Javascript
用jquery实现学校的校历(asp.net+jquery ui 1.72)
2010/01/01 Javascript
javascript中运用闭包和自执行函数解决大量的全局变量问题
2010/12/30 Javascript
js变量以及其作用域详解
2020/07/18 Javascript
ajax中get和post的说明及使用与区别
2012/12/23 Javascript
使用Post提交时须将空格转换成加号的解释
2013/01/14 Javascript
js函数中onmousedown和onclick的区别和联系探讨
2013/05/19 Javascript
一个JavaScript函数把URL参数解析成Json对象
2014/09/24 Javascript
js ajaxfileupload.js上传报错的解决方法
2016/05/05 Javascript
前端实现文件的断点续传(前端文件提交+后端PHP文件接收)
2016/11/04 Javascript
js canvas仿支付宝芝麻信用分仪表盘
2016/11/16 Javascript
在vue中使用SockJS实现webSocket通信的过程
2018/08/29 Javascript
详解在vue-test-utils中mock全局对象
2018/11/07 Javascript
Vue中UI组件库之Vuex与虚拟服务器初识
2019/05/07 Javascript
react 组件传值的三种方法
2019/06/03 Javascript
使用flow来规范javascript的变量类型
2019/09/12 Javascript
JS立即执行的匿名函数用法分析
2019/11/04 Javascript
JavaScript HTML DOM 元素 (节点)新增,编辑,删除操作实例分析
2020/03/02 Javascript
maptalks+three.js+vue webpack实现二维地图上贴三维模型操作
2020/08/10 Javascript
vue+openlayers绘制省市边界线
2020/12/24 Vue.js
详解template标签用法(含vue中的用法总结)
2021/01/12 Vue.js
js实现简单商品筛选功能
2021/02/02 Javascript
Python删除Java源文件中全部注释的实现方法
2017/08/30 Python
Python如何快速上手? 快速掌握一门新语言的方法
2017/11/14 Python
python实现微信小程序自动回复
2018/09/10 Python
Python函数装饰器实现方法详解
2018/12/22 Python
python3中替换python2中cmp函数的实现
2019/08/20 Python
tensorflow2.0的函数签名与图结构(推荐)
2020/04/28 Python
html5 实现客户端验证上传文件的大小(简单实例)
2016/05/15 HTML / CSS
TIME时代杂志台湾总代理:台时亚洲
2018/10/22 全球购物
意大利一家专营包包和配饰的网上商店:Borse Last Minute
2019/08/26 全球购物
飘柔洗发水广告词
2014/03/14 职场文书
法人任命书范本
2014/06/04 职场文书
市场营销专业毕业生求职信
2014/07/21 职场文书