您当前的位置: 首页 >  Python

令狐掌门

暂无认证

  • 1浏览

    0关注

    513博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

python运算符重载

令狐掌门 发布时间:2020-03-15 15:25:28 ,浏览量:1

      python 和 C++ 一样,都支持运算符重载,python提供了内置重载方法,如果想重载,直接重写改方法即可,如下所示:

 __add__(self, other)加法 __sub__(self,other) 减法__mul__(self,other)乘法__truediv__(self,other)除法__floordiv__(self,other)地板除__mod__(self,other)取模(求余)__pow__(self,other)幂运算

       例如,里面是一个向量类Vector,重写了加法,和减法,其它的也可以一样的写。

class Vector:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __str__(self):
        return 'Vector (%d, %d)' % (self.a, self.b)

    #加号运算符重载
    def __add__(self, other):
        print("向量加法运算")
        return Vector(self.a + other.a, self.b + other.b)

    #减法运算重载
    def __sub__(self, other):
        print("向量减法运算")
        return Vector(self.a - other.a, self.b - other.b)

     测试代码:

v1 = Vector(2, 10)
v2 = Vector(5, -2)
print(v1.__str__())
print(v2.__str__())
print(v1 + v2)
print(v1-v2)

     结果

     写起来比C++方便。

关注
打赏
1652240117
查看更多评论
立即登录/注册

微信扫码登录

0.0487s