一个简单的例子——我想用一个point类来描述二维空间中的一个点。我想把两点加在一起。。。以及将两个点相乘(不要问我为什么),或将一个点乘以一个标量。现在,我将只把它当作标量是整数来实现,但分数或浮点数也很容易实现。
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __str__(self):
return "({0},{1})".format(self.x, self.y)
def __add__(self, other):
x = self.x + other.x
y = self.y + other.y
return Point(x, y)
def __mul__(self, other):
if isinstance(other, Point):
x = self.x * other.x
y = self.y * other.y
return Point(x, y)
elif isinstance(other, int):
x = self.x * other
y = self.y * other
return Point(x, y)
>>> p1 = Point(2, 3)
>>> p2 = Point(-1, 2)
>>> print(p1*p2)
(-2,6)
>>>print(p1*4)
(8,12)
但当我反转标量和点对象的顺序时,它不起作用:
>>>print(4*p1)
Traceback (most recent call last):
File "<input>", line 1, in <module> TypeError: unsupported operand type(s) for *:
'int' and 'Point'
如果我写的是'4*p1'或'p1*4',我仍然会执行相同的代码并返回相同的答案,那么我如何编写代码呢?我是否通过重载
骡子
整数对象的运算符还是有其他方法?
注意:我的简短示例的代码是从
https://www.programiz.com/python-programming/operator-overloading