一.加减乘除
加__add__(self,other)
减__sub__(self,other)
乘__mul__(self,other)
真除__truediv__(self,other)
地板除__floordiv__(self,other)
class Point:
def __init__(self,x,y):
self.x = x
self.y = y
def __add__(self,other):
self.x = self.x + other.x
self.y = self.y + other.y
二.反运算符
例如加__radd__(self,other)
如果出现 3 - b 这样的算式,程序就开始调用 b 的radd
函数
class Nint(int):
def __rsub__(self,other):
return int.__sub__(other,self)
3 - b中3不是对象,所以开始调用b的反运算
这个代码中我们return int.__sub__(other,self)
把other
和self
换了个位置
所以才是 3 - 5
other 就是 3
self 就是 5