python中的def add(self, other):就是对加法(+)重载,如下代码
def __add__(self, other): #重载+号
r=Vecter()
r.x=self.x+other.x
r.y=self.y+other.y
r.z=self.z+other.z
return r
self.x指的是实例对象t1的属性值
other.x指的是实例对象t2的属性值
例如创建一个三维向量类,实现向量的加法,减法等
代码如下:
class Vecter:
def __init__(self,x=0,y=0,z=0): #构造
self.x=x
self.y=y
self.z=z
def __add__(self, other): #重载+号
r=Vecter()
r.x=self.x+other.x
r.y=self.y+other.y
r.z=self.z+other.z
return r
def __sub__(self, other): #重载减法-
r=Vecter()
r = Vecter()
r.x = self.x - other.x
r.y = self.y - other.y
r.z = self.z - other.z
return r
def __mul__(self, other): #乘
r = Vecter()
r = Vecter()
r.x = self.x * other
r.y = self.y * other
r.z = self.z * other
return r
def __truediv__(self, other): #除
r = Vecter()
r = Vecter()
r.x = self.x / other
r.y = self.y / other
r.z = self.z / other
return r
def __floordiv__(self, other): #整除
r = Vecter()
r = Vecter()
r.x = self.x // other
r.y = self.y // other
r.z = self.z // other
return r
def show(self): #打印结果
print((self.x,self.y,self.z))
def add1(self):
self.x=self.x+1
self.y=self.y+1
self.z=self.z+1
#程序从这里开始运行
v1=Vecter(1,2,3)
v2=Vecter(4,5,6)
v3=v1+v2
v3.show()
v4=v1-v2
v4.show()
v5=v3*2
v5.show()
v6=v2/2
v6.show()
v1.add1()
v1.show()
输出结果如下:
D:\python\python.exe "D:/应用/PyCharm Community Edition 2020.3.4/pythonProject3/second.py"
(5, 7, 9)
(-3, -3, -3)
(10, 14, 18)
(2.0, 2.5, 3.0)
(2, 3, 4)
Process finished with exit code 0
可以简单理解为重新定义了加法等运算方式