Python 运算符重载中__add__(self,other)

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

可以简单理解为重新定义了加法等运算方式

  • 12
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

开始King

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值