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++方便。