运算符重载中"/>
Python 运算符重载中
python中的def add(self, other):就是对加法(+)重载,如下代码
def __add__(self, other): #重载+号r=Vecter()r.x=self.x+other.xr.y=self.y+other.yr.z=self.z+other.zreturn r
self.x指的是实例对象t1的属性值
other.x指的是实例对象t2的属性值
例如创建一个三维向量类,实现向量的加法,减法等
代码如下:
class Vecter:def __init__(self,x=0,y=0,z=0): #构造self.x=xself.y=yself.z=zdef __add__(self, other): #重载+号r=Vecter()r.x=self.x+other.xr.y=self.y+other.yr.z=self.z+other.zreturn rdef __sub__(self, other): #重载减法-r=Vecter()r = Vecter()r.x = self.x - other.xr.y = self.y - other.yr.z = self.z - other.zreturn rdef __mul__(self, other): #乘r = Vecter()r = Vecter()r.x = self.x * otherr.y = self.y * otherr.z = self.z * otherreturn rdef __truediv__(self, other): #除r = Vecter()r = Vecter()r.x = self.x / otherr.y = self.y / otherr.z = self.z / otherreturn rdef __floordiv__(self, other): #整除r = Vecter()r = Vecter()r.x = self.x // otherr.y = self.y // otherr.z = self.z // otherreturn rdef show(self): #打印结果print((self.x,self.y,self.z))def add1(self):self.x=self.x+1self.y=self.y+1self.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
可以简单理解为重新定义了加法等运算方式
更多推荐
Python 运算符重载中
发布评论