总结Python常用的魔法方法


Posted in Python onMay 25, 2021

一、算数运算符的魔法方法

  • python2.2以后,对类和类型进行了统一,做法就是讲int()、float()、str()、list()、tuple()这些BIF转换为工厂函数(类对象)
  • 给出以下算数运算符对应的魔法方法,前面和后面都被双下划线包尾说明是魔法方法
运算符 对应的魔法方法 中文注释
+ __ add__(self, other) 加法
- __ sub__(self, other) 减法
* __ mul__(self, other) 乘法
/ __ truediv__(self, other) 真除法
// __ floordiv__(self, other) 整数除法
% __ mod__(self, other) 取余除法
divmod(a, b) __ divmod__(self, other) 把除数和余数运算结果结合,divmod(a,b)返回值是一个元组(a//b, a%b)
** __ pow__(self, other[,modulo]) self的other次方再对modulo取余
<< __ lshift__(self, other) 按位左移
>> __ rshift__(self, other) 按位右移
& __ and__(self, other) 按位与操作
^ __ xor__(self, other) 按位异或操作(同为0,异为1)
__ or__(self, other) 按位或操作(有1则1)
? ? ?
  • eg:
>>> type(len)
<class 'builtin_function_or_method'>            #普通的BIF
>>> type(int)
<class 'type'>             #工厂函数(类对象),当调用它们的时候,其实就是创建了一个相应的实例对象
>>> type(dir)
<class 'builtin_function_or_method'>
>>> type(list)
<class 'type'>

>>> a = int('123')        #创建一个相应的实例对象a
>>> b = int('345')
>>> a + b              #python在两个对象进行相加操作
468
  • eg:举个例子,下面定义一个比较特立独行的类:

继承int,并重写__add__方法

>>> class New_int(int):
    def __add__(self,other):
        return int.__sub__(self,other)
    def __sub__(self,other):
        return int.__add__(self,other)

    
>>> a = New_int(3)
>>> b = New_int(5)
>>> a + b    #两个对象相加,触发 __add__(self,other)方法
-2
>>> a - b
8
>>>

实例2:错误写法,会造成无限递归
>>> class New_int(int):
    def __add__(self,other):
        return (self + other)  
    def __sub__(self,other):
        return (self - other)


>>> class New_int(int):
    def __add__(self,other):
        return (int(self) + int(other))       #将self与other强制转换为整型,所以不会出现两个对象相加触发__add__()方法
    def __sub__(self,other):
        return (int(self) - int(other))

    
>>> a = New_int(3)
>>> b = New_int(5)
>>> a + b
8

二、反运算相关的魔法方法

  • 反运算相关的魔法方法
魔法方法 定义
__ radd__(self, other) 定义加法的行为:+(当左操作数不支持相应的操作时被调用)
__ rsub__(self, other) 定义减法的行为:-(当左操作数不支持相应的操作时被调用)
__ rmul__(self, other) 定义乘法的行为:*(当左操作数不支持相应的操作时被调用)
__ rtruediv__(self, other) 定义真除法的行为:/(当左操作数不支持相应的操作时被调用)
__ rfloordiv__(self, other) 定义整数除法的行为://(当左操作数不支持相应的操作时被调用)
__ rmod__(self, other) 定义取模算法的行为:%(当左操作数不支持相应的操作时被调用)
__ rdivmod__(self, other) 定义当被divmod()调用时的行为(当左操作数不支持相应的操作时被调用)
__ rpow__(self, other) 定义当被power()调用或**运算时的行为(当左操作数不支持相应的操作时被调用)
__ rlshift__(self, other) 定义按位左移位的行为:<<(当左操作数不支持相应的操作时被调用)
__ rrshift__(self, other) 定义按位右移位的行为:>>(当左操作数不支持相应的操作时被调用)
__ rand__(self, other) 定义按位与操作的行为:&(当左操作数不支持相应的操作时被调用)
__ rxor__(self, other) 定义按位异或操作的行为:^(当左操作数不支持相应的操作时被调用)
__ ror__(self, other) 定义按位或操作的行为:丨(当左操作数不支持相应的操作时被调用)
? ?
>>> class int(int):
    def __add__(self,other):
        return int.__sub__(self,other)

    
>>> a = int(3)
>>> b = int(2)
>>> a + b
1

反运算与算术运算符的不同之处是,反运算多了一个'r',例如 __add__()的反运算对应为 __radd__()

>>> a + b

这里a是加数,b是被加数,如果a对象的__add__()方法没有实现或者不支持相应的操作,那么python就会自动调用b的__radd__()方法

实例:

>>> class Nint(int):
    def __radd__(self,other):
        return int.__sub__(self,other)

    
>>> a = Nint(5)
>>> b = Nint(3)
>>> a + b      #由于a对象默认有__add__()方法,所以b的__radd__()没有执行
8

实例2:

>>> class Nint(int):
    def __radd__(self,other):
        return int.__sub__(self,other)

    
>>> b = Nint(5)
>>> 3 + b         #由于3无__add__()方法,所以执行b的反运算__radd__(self,other)方法,其中self是b对象
2

eg:注:在重写反运算魔法方法时,一定要注意顺序问题。得到的应该是个负数,所以顺序改变下。

总结Python常用的魔法方法 

三、增量赋值运算

增量赋值运算的魔法方法

魔法方法 定义
__ iadd__(self, other) 定义赋值加法的行为:+=
__ isub__(self, other) 定义赋值减法的行为:-=
__ imul__(self, other) 定义赋值乘法的行为:*=
__ itruediv__(self, other) 定义赋值真除法的行为:/=
__ ifloordiv__(self, other) 定义赋值整数除法的行为://=
__ imod__(self, other) 定义赋值取模算法的行为:%=
__ ipow__(self, other) 定义赋值幂运算的行为:**=
__ ilshift__(self, other) 定义赋值按位左移位的行为:<<=
__ irshift__(self, other) 定义赋值按位右移位的行为:>>=
__ iand__(self, other) 定义赋值按位与操作的行为:&=
__ ixor__(self, other) 定义赋值按位异或操作的行为:^=
__ ior__(self, other) 定义赋值按位或操作的行为:丨=
- -

四、一元操作符

  • 一元操作符的魔法方法
魔法方法 定义
__ neg__(self) 定义正号的行为:+x
__ pos__(self) 定义负号的行为:-x
__ abs__(self) 定义当被abs()调用时的行为
__ invert__(self) 定义按位求反的行为:~x
? ?

到此这篇关于总结Python常用的魔法方法的文章就介绍到这了,更多相关Python魔法方法内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
Windows系统下安装Python的SSH模块教程
Feb 05 Python
Python的__builtin__模块中的一些要点知识
May 02 Python
Python基于DES算法加密解密实例
Jun 03 Python
Python 字典与字符串的互转实例
Jan 13 Python
Python学习教程之常用的内置函数大全
Jul 14 Python
python Spyder界面无法打开的解决方法
Apr 27 Python
Python微信操控itchat的方法
May 31 Python
Python3 Tkinkter + SQLite实现登录和注册界面
Nov 19 Python
python名片管理系统开发
Jun 18 Python
python装饰器三种装饰模式的简单分析
Sep 04 Python
tensorflow学习笔记之tfrecord文件的生成与读取
Mar 31 Python
python实现会员管理系统
Mar 18 Python
Python入门学习之类的相关知识总结
python munch库的使用解析
May 25 #Python
python调试工具Birdseye的使用教程
浅谈Python numpy创建空数组的问题
May 25 #Python
python实现语音常用度量方法的代码详解
python基础学习之生成器与文件系统知识总结
May 25 #Python
Python实战之实现简易的学生选课系统
May 25 #Python
You might like
中国收音机工业发展史
2021/03/02 无线电
PHP 分页原理分析,大家可以看看
2009/12/21 PHP
使用php+Ajax实现唯一校验实现代码[简单应用]
2011/11/29 PHP
yii框架表单模型使用及以数组形式提交表单数据示例
2014/04/30 PHP
PHP实现将上传图片自动缩放到指定分辨率,并保持清晰度封装类示例
2019/06/17 PHP
鼠标滚轮改变图片大小的示例代码
2013/11/20 Javascript
使用Raygun对Node.js应用进行错误处理的方法
2015/06/23 Javascript
跟我学习javascript的this关键字
2020/05/28 Javascript
基于jquery实现的鼠标悬停提示案例
2016/12/11 Javascript
原生js获取浏览器窗口及元素宽高常用方法集合
2017/01/18 Javascript
gulp加批处理(.bat)实现ng多应用一键自动化构建
2017/02/16 Javascript
浅析JavaScript中var that=this
2017/02/17 Javascript
走进javascript——不起眼的基础,值和分号
2017/02/24 Javascript
Angular获取手机验证码实现移动端登录注册功能
2017/05/17 Javascript
webpack学习--webpack经典7分钟入门教程
2017/06/28 Javascript
Angular实现的table表格排序功能完整示例
2017/12/22 Javascript
JS实现前端动态分页码代码实例
2020/06/02 Javascript
使用Python的内建模块collections的教程
2015/04/28 Python
Python实现的文本编辑器功能示例
2017/06/30 Python
python实现自动解数独小程序
2019/01/21 Python
利用ctypes获取numpy数组的指针方法
2019/02/12 Python
Python静态类型检查新工具之pyright 使用指南
2019/04/26 Python
python 自定义装饰器实例详解
2019/07/20 Python
Python OpenCV调用摄像头检测人脸并截图
2020/08/20 Python
python使用 request 发送表单数据操作示例
2019/09/25 Python
Python实现线性插值和三次样条插值的示例代码
2019/11/13 Python
Python如何基于smtplib发不同格式的邮件
2019/12/30 Python
Python sorted对list和dict排序
2020/06/09 Python
基于K.image_data_format() == 'channels_first' 的理解
2020/06/29 Python
百思买美国官网:Best Buy
2016/07/28 全球购物
马来西亚时装购物网站:ZALORA马来西亚
2017/03/14 全球购物
可爱的童装和鞋子:Fabkids
2019/08/16 全球购物
serialVersionUID具有什么样的特征
2014/02/20 面试题
文明学生标兵事迹
2014/01/21 职场文书
房屋买卖委托公证书
2014/04/08 职场文书
企业优秀员工事迹材料
2014/05/28 职场文书