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编程中对文件和存储器的读写示例
Jan 25 Python
Python操作Excel之xlsx文件
Mar 24 Python
Python数据结构与算法之使用队列解决小猫钓鱼问题
Dec 14 Python
Python实现判断字符串中包含某个字符的判断函数示例
Jan 08 Python
scrapy爬虫完整实例
Jan 25 Python
Python实现图片尺寸缩放脚本
Mar 10 Python
Python3 单行多行万能正则匹配方法
Jan 07 Python
Python学习笔记之While循环用法分析
Aug 14 Python
深入理解Tensorflow中的masking和padding
Feb 24 Python
Python 实现将大图切片成小图,将小图组合成大图的例子
Mar 14 Python
Python基础之数据类型知识汇总
May 18 Python
人工智能深度学习OpenAI baselines的使用方法
May 20 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
阿拉伯的咖啡与水烟
2021/03/03 咖啡文化
php程序之die调试法 快速解决错误
2009/09/17 PHP
php的大小写敏感问题整理
2011/12/29 PHP
PHP实现的构造sql语句类实例
2016/02/03 PHP
如何实现浏览器上的右键菜单
2006/07/10 Javascript
JavaScript可否多线程? 深入理解JavaScript定时机制
2012/05/23 Javascript
jquery 获取表单元素里面的值示例代码
2013/07/28 Javascript
js中一维数组和二位数组中的几个问题示例说明
2014/07/17 Javascript
jquery实现上下左右滑动的方法
2015/02/09 Javascript
原生JavaScript实现滚动条效果
2020/03/24 Javascript
使用jQuery处理AJAX请求的基础学习教程
2016/05/10 Javascript
nodejs async异步常用函数总结(推荐)
2017/11/17 NodeJs
vue实现文章内容过长点击阅读全文功能的实例
2017/12/28 Javascript
vue组件的写法汇总
2018/04/12 Javascript
React 组件间的通信示例
2018/06/14 Javascript
SVG实现时钟效果
2018/07/17 Javascript
[01:10:57]Liquid vs OG 2018国际邀请赛小组赛BO2 第一场 8.16
2018/08/17 DOTA
Python多线程编程(四):使用Lock互斥锁
2015/04/05 Python
python+selenium识别验证码并登录的示例代码
2017/12/21 Python
Python列表推导式与生成器表达式用法示例
2018/02/08 Python
对python中两种列表元素去重函数性能的比较方法
2018/06/29 Python
python实现爬取图书封面
2018/07/05 Python
python实现京东秒杀功能
2018/07/30 Python
python安装twisted的问题解析
2018/08/21 Python
python ddt数据驱动最简实例代码
2019/02/22 Python
python socket通信编程实现文件上传代码实例
2019/12/14 Python
使用PyTorch训练一个图像分类器实例
2020/01/08 Python
Python面向对象编程基础实例分析
2020/01/17 Python
python动态文本进度条的实例代码
2020/01/22 Python
详解Python中的GIL(全局解释器锁)详解及解决GIL的几种方案
2021/01/29 Python
CSS Grid布局教程之网格单元格布局
2014/12/30 HTML / CSS
程序员跳槽必看面试题总结
2013/06/28 面试题
寒假家长评语大全
2014/04/16 职场文书
档案保密承诺书
2014/06/03 职场文书
高效课堂教学反思
2016/02/24 职场文书
pytorch 中nn.Dropout的使用说明
2021/05/20 Python