算数运算方法 、反运算方法
以对象A+对象B为例,都是将A作为self值,而B作为other值传入__add__(self,other)方法;
当用户输入A+B,就会调用重写的add方法;
>>>class Nint(int):
def __add__(self,other):
return int.__sub__(self,other)
def __sub__(self,other):
return int.__add__(self,other)
>>>A=Nint(5)
>>>B=Nint(2)
>>>print(A-B)
7
>>>print(A+B)
3
但当A对象的算术运算未实现或不支持相应的操作的时候,Python就会自动调用B的radd方法
其中B的radd方法指的是将B的值作为self,将A的值作为other