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调用windows api锁定计算机示例
Apr 17 Python
Python设计模式之中介模式简单示例
Jan 09 Python
python实现excel读写数据
Mar 02 Python
flask框架使用orm连接数据库的方法示例
Jul 16 Python
python实现树的深度优先遍历与广度优先遍历详解
Oct 26 Python
Python3 中作为一等对象的函数解析
Dec 11 Python
python误差棒图errorbar()函数实例解析
Feb 11 Python
TensorBoard 计算图的可视化实现
Feb 15 Python
django 模型中的计算字段实例
May 19 Python
python 字符串的驻留机制及优缺点
Jun 19 Python
python如何提升爬虫效率
Sep 27 Python
Python类型转换的魔术方法详解
Dec 23 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 file_exists 检查文件或目录是否存在的函数
2010/05/10 PHP
PHP 日志缩略名的创建函数代码
2010/05/26 PHP
PHP中static关键字原理的学习研究分析
2011/07/18 PHP
基于php split()函数的用法详解
2013/06/05 PHP
PHP修改session_id示例代码
2014/01/08 PHP
PHP中常用的字符串格式化函数总结
2014/11/19 PHP
PHP file_get_contents函数读取远程数据超时的解决方法
2015/05/13 PHP
学习php设计模式 php实现合成模式(composite)
2015/12/08 PHP
jquery ajax 检测用户注册时用户名是否存在
2009/11/03 Javascript
javascript字符串拼接的效率问题
2010/12/25 Javascript
Jquery实现图片放大镜效果的思路及代码(自写)
2013/10/18 Javascript
JS取文本框中最小值的简单实例
2013/11/29 Javascript
js实现最短的XML格式化工具实例
2015/03/12 Javascript
javascript字符串循环匹配实例分析
2015/07/17 Javascript
JavaScript的Polymer框架中dom-repeat与VM的相关操作
2015/07/29 Javascript
jQuery基于muipicker实现仿ios时间选择
2016/02/22 Javascript
内容滑动切换效果jquery.hwSlide.js插件封装
2016/07/07 Javascript
jQuery快速高效制作网页交互特效
2017/02/24 Javascript
JavaScript实现动态增删表格的方法
2017/03/09 Javascript
vue里面父组件修改子组件样式的方法
2018/02/03 Javascript
VSCode中如何利用d.ts文件进行js智能提示
2018/04/13 Javascript
layui实现数据表格自定义数据项
2019/10/26 Javascript
为react组件库添加typescript类型提示的方法
2020/06/15 Javascript
Python实现读取并保存文件的类
2017/05/11 Python
python anaconda 安装 环境变量 升级 以及特殊库安装的方法
2017/06/21 Python
Python异常对代码运行性能的影响实例解析
2018/02/08 Python
Python面向对象之继承和组合用法实例分析
2018/08/27 Python
网页切图的CSS和布局经验与要点
2015/04/09 HTML / CSS
如何用border-image实现文字气泡边框的示例代码
2020/01/21 HTML / CSS
巴西家用小家电购物网站:Polishop
2016/08/07 全球购物
房产转让协议书
2014/04/11 职场文书
陈安之励志演讲稿
2014/08/21 职场文书
2015年化验室工作总结
2015/04/23 职场文书
2015年财政局工作总结
2015/05/21 职场文书
Go语言切片前或中间插入项与内置copy()函数详解
2021/04/27 Golang
MySQL数据库实验之 触发器和存储过程
2022/06/21 MySQL