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中if语句的嵌套用法
May 14 Python
python运行时间的几种方法
Jun 17 Python
Python中如何获取类属性的列表
Dec 26 Python
python去除字符串中的换行符
Oct 11 Python
分析python切片原理和方法
Dec 19 Python
Django视图和URL配置详解
Jan 31 Python
Python实现的根据文件名查找数据文件功能示例
May 02 Python
Python爬虫之网页图片抓取的方法
Jul 16 Python
python之super的使用小结
Aug 13 Python
python实现机器学习之元线性回归
Sep 06 Python
Python运行DLL文件的方法
Jan 17 Python
浅谈Pytorch中的自动求导函数backward()所需参数的含义
Feb 29 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 sprintf() 函数的应用(定义和用法)
2012/06/29 PHP
PHP中的替代语法介绍
2015/01/09 PHP
详谈php ip2long 出现负数的原因及解决方法
2017/04/05 PHP
PHP simplexml_load_file()函数讲解
2019/02/03 PHP
Date对象格式化函数代码
2010/07/17 Javascript
javascript实现可改变滚动方向的无缝滚动实例
2013/06/17 Javascript
nodejs获取本机内网和外网ip地址的实现代码
2014/06/01 NodeJs
Javascript 拖拽的一些高级的应用(逐行分析代码,让你轻松了拖拽的原理)
2015/01/23 Javascript
asp.net中oracle 存储过程(图文)
2015/08/12 Javascript
NodeJS仿WebApi路由示例
2017/02/28 NodeJs
ES6基础之数组和对象的拓展实例详解
2019/08/22 Javascript
使用JavaScript获取Django模板指定键值数据
2020/05/27 Javascript
python定时采集摄像头图像上传ftp服务器功能实现
2013/12/23 Python
Python实现的石头剪子布代码分享
2014/08/22 Python
python批量设置多个Excel文件页眉页脚的脚本
2018/03/14 Python
老生常谈python中的重载
2018/11/11 Python
python3中类的继承以及self和super的区别详解
2019/06/26 Python
python中列表的切片与修改知识点总结
2019/07/23 Python
python滑块验证码的破解实现
2019/11/10 Python
在django-xadmin中APScheduler的启动初始化实例
2019/11/15 Python
使用Python第三方库pygame写个贪吃蛇小游戏
2020/03/06 Python
使用python图形模块turtle库绘制樱花、玫瑰、圣诞树代码实例
2020/03/16 Python
Python控制鼠标键盘代码实例
2020/12/08 Python
OpenCV+python实现膨胀和腐蚀的示例
2020/12/21 Python
利用html5的websocket实现websocket聊天室
2013/12/12 HTML / CSS
Burberry英国官网:英国标志性奢侈品牌
2017/03/29 全球购物
德国著名廉价网上药店:Shop-Apotheke
2017/07/23 全球购物
Marc O’Polo俄罗斯官方在线商店:德国高端时尚品牌
2019/12/26 全球购物
期终自我鉴定
2014/02/17 职场文书
文明寝室标语
2014/06/13 职场文书
党的群众路线对照检查材料
2014/09/22 职场文书
幼儿园综治宣传月活动总结
2015/05/07 职场文书
2019西餐厅创业计划书范文!
2019/07/12 职场文书
导游词之杭州岳王庙
2019/11/13 职场文书
JavaScript 事件捕获冒泡与捕获详情
2021/11/11 Javascript
canvas 中如何实现物体的框选
2022/08/05 Javascript