您的位置:首页 > 编程语言 > Python开发

鱼c笔记——Python魔法方法二:算数运算

2018-02-04 15:51 471 查看
Python的魔法方法还提供了让我们自定义对象的数值处理,通过对所提供的魔法方法的重写,我们可以自定义任何对象之间的算数运算。

关于算数的魔法方法:当我们的对象进行相关算数运算的时候,会自然而然的触发对应的魔法方法。一旦我们重写了这些魔法方法,Python就会根据我们的意图进行计算。

>>> class New_int(int):
def __add__(self, other):
return int.__sub__(self, other) #当然这里也可以不去调用int的魔法方法,不过这样做要格外小心,详见下例
def __sub__(self, other):
return int.__add__(self, other)

>>> a = New_int(3)
>>> b = New_int(5)
>>> a + b #看到是+,会自动调用a的__add__方法
-2
>>> a - b
8

笔者顺嘴一提:想要查看__add__方法的使用,可以用help(int.__add__)查看。
想要查看int的所有内置方法可以用dir(int) 或 help(int)

>>> class Try_int(int):
def __add__(self, other):
return self + other #解决方法:可以改为int(self) + int(other)
def __sub__(self, other):
return self - other

>>> a = Try_int(3)
>>> b = Try_int(5)
>>> a + b #看到+去调用a的__sub__方法,调用add返回的是self+other,而self是实例化对象绑定的一个方法,self事实上就是绑定了a进来,other是加法右边的一个数,造成了无限递归
Traceback (most recent call last):
File "<pyshell#39>", line 1, in <module>
a + b
File "<pyshell#36>", line 3, in __add__
return self + other
File "<pyshell#36>", line 3, in __add__
return self + other
File "<pyshell#36>", line 3, in __add__
return self + other
[Previous line repeated 327 more times]
RecursionError: maximum recursion depth exceeded while calling a Python object

通过对指定魔法方法的重写,我们可以让Python根据我们的意图来实现程序。

a + b    #当a的加法运算没有实现或不支持的时候, 会实现b的相应的加法反运算操作符

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

>>> a = Nint(3)
>>> b = Nint(5)

>>> a + b #正常
8

>>> 1 + b #找不到1的__add__方法,就去找b的加法反运算
4
参考阅读:http://bbs.fishc.com/thread-48793-1-1.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: