我们有时候需要对自己的类对象使用运算符进行操作,希望能够像C++那样实现运算符重载,那么就可以重载一下Python的一些方法来实现。
以加法为例,Python中只需要在类对象中重载一下__add__(self, other)
方法即可:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return "(" + str(self.x) + ", " + str(self.y) + ")"
def __add__(self, other):
self.x += other.x
self.y += other.y
return self
point1 = Point(1, 2)
point2 = Point(2, 4)
print(point1 + point2)
print(point1)
print(point2)
注意,在__add__(self, other)
这里我的返回值是return self
,这也就意味着,我是改变了加法前面的那个类对象的值。
可以看到,point1的值变了,而point2的值没变。
如果想要实现的效果是加法结束以后,加法两侧的值都不改变,则可以将__add__(self, other)
方法的返回值改成:
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
同样的还有其他重载运算符的方法:
def __add__(self, other):
def __sub__(self, other):
def __mul__(self, other):
def __matmul__(self, other):
def __truediv__(self, other):
def __floordiv__(self, other):
def __mod__(self, other):
def __divmod__(self, other):
def __pow__(self, power, modulo=None):
def __lshift__(self, other):
def __rshift__(self, other):
def __and__(self, other):
def __or__(self, other):
def __xor__(self, other):
def __radd__(self, other):
def __rsub__(self, other):
def __rmul__(self, other):