Python 运算符重载中

编程入门 行业动态 更新时间:2024-10-05 03:18:22

Python <a href=https://www.elefans.com/category/jswz/34/1771114.html style=运算符重载中"/>

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 运算符重载中

本文发布于:2024-02-14 14:12:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1763465.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:运算符   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!