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 相关文章推荐
Django中实现点击图片链接强制直接下载的方法
May 14 Python
Django自定义过滤器定义与用法示例
Mar 22 Python
numpy中实现ndarray数组返回符合特定条件的索引方法
Apr 17 Python
Python高级用法总结
May 26 Python
浅谈django三种缓存模式的使用及注意点
Sep 30 Python
python爬取网易云音乐评论
Nov 16 Python
python学生管理系统
Jan 30 Python
PyCharm2018 安装及破解方法实现步骤
Sep 09 Python
Django之form组件自动校验数据实现
Jan 14 Python
彻底解决Python包下载慢问题
Nov 15 Python
python实现三种随机请求头方式
Jan 05 Python
Python matplotlib绘制雷达图
Apr 13 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
使用Apache的rewrite技术
2006/06/22 PHP
mysql下创建字段并设置主键的php代码
2010/05/16 PHP
PHP遍历目录并返回统计目录大小
2014/06/09 PHP
php用户登录之cookie信息安全分析
2016/05/13 PHP
Yii框架通过请求组件处理get,post请求的方法分析
2019/09/03 PHP
ThinkPHP类似AOP思想的参数验证的实现方法
2019/12/18 PHP
javascript字典探测用户名工具
2006/10/05 Javascript
javascript 添加和移除函数的通用方法
2009/10/20 Javascript
写了10年的Javascript也未必全了解的连续赋值运算
2011/03/25 Javascript
JS实现随机化快速排序的实例代码
2013/08/01 Javascript
js中的push和join方法使用介绍
2013/10/08 Javascript
jQuery实现响应浏览器缩放大小并改变背景颜色
2014/10/31 Javascript
jQuery中toggleClass()方法用法实例
2015/01/05 Javascript
Easyui的组合框的取值与赋值
2016/10/28 Javascript
jquery 追加元素append、prepend、before、after用法与区别分析
2016/12/02 Javascript
微信小程序-拍照或选择图片并上传文件
2017/01/06 Javascript
angularjs 实现带查找筛选功能的select下拉框实例
2017/01/11 Javascript
微信小程序icon组件使用详解
2018/01/31 Javascript
详解react-redux插件入门
2018/04/19 Javascript
详解vue-cli中模拟数据的两种方法
2018/07/03 Javascript
vue中子组件的methods中获取到props中的值方法
2018/08/27 Javascript
解决基于 keep-alive 的后台多级路由缓存问题
2020/12/23 Javascript
用python实现的可以拷贝或剪切一个文件列表中的所有文件
2009/04/30 Python
介绍Python的Urllib库的一些高级用法
2015/04/30 Python
python散点图实例之随机漫步
2018/08/27 Python
python字典的遍历3种方法详解
2019/08/10 Python
python实现测试工具(一)——命令行发送get请求
2020/10/19 Python
html5 sessionStorage会话存储_动力节点Java学院整理
2017/07/06 HTML / CSS
携程英文网站:Trip.com
2017/02/07 全球购物
物业保安主管岗位职责
2013/12/25 职场文书
信访工作者先进事迹
2014/01/17 职场文书
优秀员工表扬信
2014/01/17 职场文书
《故乡》教学反思
2014/04/10 职场文书
高中英语演讲稿范文
2014/04/24 职场文书
部队2015年终工作总结
2015/04/02 职场文书
家装业务员岗位职责
2015/04/03 职场文书