第8.21节 Python中__lt__、__gt__等 “富比较”(“rich comparison”)方法用途探究

Python中的[__gt__之间的关联关系分析 通过实现该方法,我们可以根据自定义的逻辑来比较对象,并得出相应的比较结果。它是Python内置的特殊方法之一,用于比较两个对象之间的关联关系。该方法接受另一个对象作为参数,并返回一个布尔值,表示当前对象是否大于所传入的对象。"方法还可以用于其他类型的关联关系分析,例如字符串的大小比较、数字的大小比较等。如果当前学生的年龄大于所传入的学生对象的年龄,则返回。的类,表示学生对象,其中包含学生的姓名和年龄属性。根据学生对象的年龄属性,我们可以判断出其中的大于关系。"方法进行关联关系分析,并提供相应的源代码示例。 阅读详情

一、 富比较方法
Python的基类object提供一系列可以用于实现同类对象进行“比较”的方法,可以用于同类对象的不同实例进行比较。他们也是实例方法,定义如下:
object.lt(self, other)
object.le(self, other)
object.eq(self, other)
object.ne(self, other)
object.gt(self, other)
object.ge(self, other)
其中self是指对象自身,other是参与比较的另一对象,返回值最好为bool值,也可以是任意值。
以上这些方法,object类实现了__eq__和__ne__两个方法,lt、le、gt、__ge__这些方法默认返回值为“NotImplemented”,需要自定义类实现这些方法才能正确使用这些方法,当然__eq__和__ne__这两个方法也可以重写。

二、 富比较方法的使用
这些特殊方法除了直接调用外,当用运算符进行对象比较时也会被调用,运算符号与方法名称的对应关系如下:x<y 调用 x.__lt__(y)、x<=y 调用 x.__le__(y)、x==y 调用 x.__eq__(y)、x!=y 调用 x.__ne__(y)、x>y 调用 x.__gt__(y)、x>=y 调用 x.__ge__(y)。比较运算符之间没有其他隐含关系,例如 (x<y or x==y) 为真并不意味着 x<=y。具体要看实现的方法。
如果指定的参数对没有相应的实现,富比较方法可能会返回单例对象 NotImplemented。按照惯例,成功的比较会返回 False 或 True。不过实际上这些方法可以返回任意值,因此如果比较运算符是要用于布尔值判断(例如作为 if 语句的条件),Python 会对返回值调用 bool() 以确定结果为真还是假。
具体实现时,编程者可以根据一定的业务规则来设置两个对象的一个或多个属性经过运算后的比较,根据比较结果确认返回值。这些方法在支持复杂的数学运算类型对象、排序类型对象进行比较时非常有用,开发人员可以根据自己的需要定制”大和小”的判断规则。

本节简单介绍了Python的富比较方法,在此暂时不介绍相关实现案例,大家可以自己动手练习一下。下节将介绍重写相关方法的案例。

老猿Python,跟老猿学Python!
博客地址:https://blog.youkuaiyun.com/LaoYuanPython

请大家多多支持,点赞、评论和加关注!谢谢!

富比较方法的用途探究 - Python 富比较(Rich Comparison)是一种在Python中常用的方法,用于比较对象的相对大小或相等性。通过实现富比较方法,我们可以定义对象之间的比较行为,例如大于、小于、等于等操作。通过实现富比较方法,我们可以自定义对象之间的比较操作,包括大小比较和相等性比较。在实际应用中,富比较方法为我们提供了一种灵活的方式来定义自定义对象的比较行为。通过实现这些方法,我们可以根据对象的特定属性或行为进行比较,从而满足不同的业务需求。在Python中,富比较方法是通过实现一系列特殊的方法来实现的。 阅读详情

相关推荐

IGS精密星历高效获取与解析指南

本文详细介绍了IGS精密星历在高精度定位中的核心作用,对比了IGS Final、IGR和IGU等不同产品的精度与时效性差异。指南提供了从武汉大学、NASA CDDIS等数据中心高效下载数据的实战方法,并深入解析了SP3文件格式,帮助用户掌握精密星历的获取、解析与自动化处理技巧,以支持厘米级定位应用。

garlic的博客 839

python的lt魔术方法怎么用

Python 中的 __lt__ 方法是对应于小于运算符 &lt; 的魔术方法(称作运算符重载)。使用方法如下: 在自定义的类中定义 __lt__ 方法,类似于其他的方法。 在定义 __lt__ 方法时,需要接收一个参数,表示另一个与当前对象进行比较的对象。 在 __lt__ 方法中,进行对当前对象和参数对象的比较,并返回一个布尔值,表示当前对象是否小于参数对象。 例如,如果我们想定义一...

weixin_35755823的博客 2192

CSM中一些常见问题的解决方式

CSM中一些常见问题的解决方式 抖动 摄像机在每帧移动或者旋转时,会产生较严重的抖动问题。

小龙虾的博客 2130

Python小技巧:富比较方法的妙用,__lt__、__le__、__eq__、__ne__、__gt__、__ge__。。。

Python小技巧,介绍以及重写富比较方法,__eq__, __lt__, __le__等等,知其然而知其所以然!

苟日新,日日新,又日新!!! 5982

攻防世界 web高手进阶区 9分题 Web_python_flask_sql_injection

继续ctf的旅程,开始攻防世界web高手进阶区的9分题,本文是Web_python_flask_sql_injection的writeup

闵行小鱼塘 1473

MATLAB实战:手把手教你实现Gardner环路位同步(附完整代码)

本文通过MATLAB实战,详细讲解了Gardner环路位同步算法的原理与实现。内容涵盖插值滤波器、定时误差检测、环路滤波器与数控振荡器等核心模块,并提供完整代码和调试技巧,帮助读者掌握数字通信中关键的符号定时同步技术。

weixin_29048775的博客 174

Python自定义排序全解析:key函数、__lt__方法与cmp_to_key实战指南

在数据处理与算法实现中,排序是基础且核心的操作,它决定了数据组织的效率和查询的便捷性。其原理在于通过比较元素间的特定属性,按照既定规则重新排列序列。掌握自定义排序技术能极大提升代码的灵活性与性能,尤其在处理复杂数据结构时。常见的应用场景包括多级排序(如先按时间再按优先级)、自定义规则排序(如日志级别、游戏卡牌)以及对象属性综合排序等。本文聚焦Python中的三种核心方法:通过key函数高效映射排序键,利用__lt__魔术方法实现对象自然顺序,以及借助functools.cmp_to_key处理极端复杂的双向

weixin_30475039的博客 425

YOLOv8实战:如何用Focaler-IoU提升小目标检测精度(附代码)

本文详细介绍了如何通过Focaler-IoU提升YOLOv8在小目标检测中的精度,包括核心机制解析、代码实现及调优策略。Focaler-IoU通过动态聚焦机制有效解决传统IoU对小目标检测的不足,显著提升模型性能。附有完整的代码示例和实战指南,适合计算机视觉开发者参考。

weixin_29044157的博客 362

python中的__lt__ 方法(小于符号比较方法)

在python中,__lt__ 是用于实现“小于”比较的方法。它对应的是 < 运算符。如果你希望自定义对象支持 < 比较运算,可以通过实现 __lt__ 方法来实现。在这个__lt__方法中我们可以看见other这个参数,这个指的是另一个类对象。·传入参数 :other——另一个对象。·返回值 :Ture或Flase。·方法名 : __lt__

m0_59247951的博客 783

RK3588S之CPU--benchmark(一)

本章会基于RK3588S来介绍有关CPU常用的benchmark工具及测试过程

文艺小少年的博客 1499

数据分片的三种方式:哈希、一致性哈希、按照数据范围分片

数据分片就是按照一定的规则,将数据集划分成相互独立、正交的数据子集,然后将数据子集分布到不同的节点上。通过设计合理的数据分片规则,可将系统中的数据分布在不同的物理数据库中,达到提升应用系统数据处理速度的目的。三种常用的数据分片方式:1. 哈希分片2. 一致性哈希分片(Consistent Hash)3. 按照数据范围分片(Range Based)数据分片的应用场景:1. 数据库扩展2. 分布式缓存对集群部署多个缓存节点,提高缓存的处理能力。

wjianwei666的专栏 1135

Python的富比较方法__lt__、__gt__之间的关联关系分析

Python的富比较方法包括__lt__、__gt__分别表示:小于、大于,对应的操作运算符为:“&lt;”、“&gt;”。那么是否象...

weixin_30721899的博客 2452

第一讲:halcon模板匹配捆绑测量矩形检测芯片针脚

使用halcon模板匹配捆绑测量矩形,检测位置发生变换的芯片针脚缺陷。

uiopmn1的博客 2995

Python中的魔法方法__lt__()和魔法方法__eq__()的使用举例

【代码】Python中的魔法方法__lt__()和魔法方法__eq__()的使用举例。

敲代码的小风 1229

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

为什么Python中称__lt__、__gt__等为“富比较”方法

Python中基类object提供了一系列可以用于实现同类对象进行“比较”的方法,可以用于同类对象的不同实例进行比较,包括__lt__、__gt__、__le__、__ge__、__eq__和__ne__六个方法。 那么为什么叫“富比较”(“rich comparison”)方法呢?查了相关资料,并没有看到权威的定义,老猿结合网上零星的资料,分析原因如下: Python2.1以前的比较方法只提供...

老猿Python 9591

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

python里class中gt 和 it 方法_Python类内置方法

内置方法说明__init__(self,...)初始化对象,在创建新对象时调用__del__(self)释放对象,在对象被删除之前调用__new__(cls,*args,**kwd)实例的生成操作__str__(self)在使用print语句时被调用__getitem__(self,key)获取序列的索引key对应的值,等价于seq[key]__len__(self)在调用内联函数len()时被调...

weixin_26712065的博客 2196

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er &lt; 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er &lt; 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er&lt;0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er &lt; 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er &lt; 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er &lt; 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er &lt; 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er &lt; 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er &lt; 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Python对象进行大小对比,重写__gt__、__eq__等方法

本文介绍了重写重写__gt__、__eq__等对象内置方法。 比较不同花色的扑克牌,按黑红梅方顺序从大到小比较,相同花色比较数值大小。 #!/usr/bin/env python # encoding: utf-8 """ @author: @license: (C) Copyright 2013-2017, Node Supply Chain Manager Corporation Limit...

a200822146085的博客 8900

【python】魔术方法大全(二)-- 比较篇

在python的内置数据结构中,比如说dict,或者list,尤其是integer、string、float,它们的rich comparison都是有良好的定义的。函数在 Python 中是非常重要的,它为我们提供了一种快速比较对象是否相等的方法,使我们能够在使用字典、集合等可哈希类型时,快速查找对象。如果y是x的衍生类,优先使用y的rich comparison的函数,否者优先使用x的函数。在python中,当你没有去写一个类的比较逻辑的时候,它默认比较两个对象的是否相等的方法是会默认调用。

海哥python的博客 1020

python __lt__ __gt__ 重载运算符

【代码】python __lt__ __gt__ 重载运算符。

TLuffy的博客 448

Python __lt__ 富比较学习

lt()

KH的博客 1万+

Python __lt__ 自定义排序

通过重写 __lt__ 方法,可以达到类似于Java中compareTo的效果

AdamShyly的博客 1058

Python魔法方法(19):__lt __(self, other)方法

Python 的对象天生拥有一些神奇的方法,它们总被双下划线所包围,它们是面向对象的 Python 的一切。它们是可以给你的类增加魔力的特殊方法,如果你的对象实现(重载)了某一个魔法方法,那么这个方法就会在特殊的情况下自动被 Python 所调用。

youzhouliu的博客 695

python3 gt,ge,eq,le,lt函数

1. 比较大小的函数 Python3中已经不能使用cmp()函数了,被如下五个函数替代: import operator #首先要导入运算符模块 operator.gt(1,2) #意思是greater than(大于) operator.ge(1,2) #意思是greater and equal(大于等于) operator.eq(1,2) #意思是equal(等于) operator.le(1,2) #意思是less and equal(小于等于) o

高压锅博客 2606

python的__lt__魔术方法

魔术方法__lt__报错,原因不明

2401_87460766的博客 401

python中lt方法_如何实现Python __lt__ __gt__自定义(重载)运算符?

Python具有神奇的方法来定义运算符的重载行为。比较运算符(,&gt; =,==和!=)可以通过为__lt __,__ le __,__ gt __,__ ge __,__ eq__和__ne__魔术方法提供定义来重载。遵循程序重载运算符以比较距离类的对象。classdistance:def__init__(self,x=5,y=5):self.ft=xself.inch=ydef__e...

weixin_39835117的博客 1632
上一篇: Python中函数是否能使用全局变量?
下一篇: 第8.22节 Python案例详解:重写 “富比较”方法控制比较逻辑
LaoYuanPython
LaoYuanPython 2020年博客之星Top3 2020年博客之星Top3 领域专家: Python技术领域 领域专家: Python技术领域
博客等级 码龄8年 15万+粉丝 1324原创
评论 4
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LaoYuanPython

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值