一、算术魔法方法的举例
1、加法(__add__)的算术运算调用减法(__sub__)的算术运算,减法(__sub__)的算术运算调用加法(__add__)的算术运算
class New_Init(int):
def __add__(self,other):return int.__sub__(self,other)
def __sub__(self,other):return int.__add__(self,other)>>> a = New_Init('5')>>> b = New_Init(6)>>> a+b-1
>>> a-b11
>>>
2、针对以上需求,现在要求不使用int方法进行运算
classTry_int(int):def __add__(self,other):return self+otherdef __sub__(self,other):return self+other>>> a = Try_int(5)>>> b = Try_int(6)>>> a+b
Traceback (most recent call last):
File"", line 1, in a+b
File"/Users/wufq/Desktop/加法算术运算.py", line 3, in __add__
return self+other
File"/Users/wufq/Desktop/加法算术运算.py", line 3, in __add__
return self+other
File"/Users/wufq/Desktop/加法算术运算.py", line 3, in __add__
return self+other
[Previous line repeated990more times]
RecursionError: maximum recursion depth exceeded#不使用int会使程序一直进行递归运算,导致内存不足
#程序改进
classTry_int(int):def __add__(self,other):return int(self)+int(other)def __sub__(self,othe