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 xml解析实例详解
Nov 14 Python
Python操作Excel之xlsx文件
Mar 24 Python
Django 使用logging打印日志的实例
Apr 28 Python
python简易远程控制单线程版
Jun 20 Python
python梯度下降法的简单示例
Aug 31 Python
Python解决线性代数问题之矩阵的初等变换方法
Dec 12 Python
python pptx复制指定页的ppt教程
Feb 14 Python
pycharm实现在虚拟环境中引入别人的项目
Mar 09 Python
django admin后管定制-显示字段的实例
Mar 11 Python
keras中epoch,batch,loss,val_loss用法说明
Jul 02 Python
使用Dajngo 通过代码添加xadmin用户和权限(组)
Jul 03 Python
如何在scrapy中集成selenium爬取网页的方法
Nov 18 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遍历文件夹与文件类及处理类用法实例
2014/09/23 PHP
PHP多维数组元素操作类的方法
2016/11/14 PHP
PHP文件与目录操作示例
2016/12/24 PHP
laravel框架的安装与路由实例分析
2019/10/11 PHP
NodeJS 模块开发及发布详解分享
2012/03/07 NodeJs
js调用图片隐藏&amp;显示实现代码
2013/09/13 Javascript
浅谈js基本数据类型和typeof
2016/08/09 Javascript
Bootstrap实现导航栏的2种方式
2016/11/28 Javascript
JavaScript模板引擎Template.js使用详解
2016/12/15 Javascript
微信小程序 页面跳转和数据传递实例详解
2017/01/19 Javascript
基于node打包可执行文件工具_Pkg使用心得分享
2018/01/24 Javascript
jQuery实现的别踩白块小游戏完整示例
2019/01/07 jQuery
JavaScript定时器设置、使用与倒计时案例详解
2019/07/08 Javascript
微信小程序实现左滑动删除效果
2020/03/30 Javascript
在vue+element ui框架里实现lodash的debounce防抖
2019/11/13 Javascript
vue3.0中使用postcss-pxtorem的具体方法
2019/11/20 Javascript
[01:21:07]EG vs Liquid 2018国际邀请赛淘汰赛BO3 第一场 8.25
2018/08/29 DOTA
python 生成不重复的随机数的代码
2011/05/15 Python
深入理解python中函数传递参数是值传递还是引用传递
2017/11/07 Python
python互斥锁、加锁、同步机制、异步通信知识总结
2018/02/11 Python
Python实现正整数分解质因数操作示例
2018/08/01 Python
Python3实现定时任务的四种方式
2019/06/03 Python
python图片二值化提高识别率代码实例
2019/08/24 Python
python保存log日志,实现用log日志画图
2019/12/24 Python
python字符串,元组,列表,字典互转代码实例详解
2020/02/14 Python
浅谈django channels 路由误导
2020/05/28 Python
CSS3的新特性介绍
2008/10/31 HTML / CSS
美国精油公司:Plant Therapy
2019/05/17 全球购物
连锁经营管理专业大学生求职信
2013/10/30 职场文书
细节决定成败演讲稿
2014/05/12 职场文书
市场营销策划方案
2014/06/11 职场文书
律政俏佳人观后感
2015/06/09 职场文书
小学英语新课改心得体会
2016/01/22 职场文书
2016年小学教师政治学习心得体会
2016/01/23 职场文书
教育教学工作反思
2016/02/24 职场文书
mysql查看表结构的三种方法总结
2022/07/07 MySQL