(当我准备提交问题时,我正在标记,并找到了答案。我认为值得在这里记录它,以便其他人可以轻松找到。)
定义
__rmul__(self, other)
.这代表正确的乘法运算。当左边的对象无法相乘时(在上面的例子中,整数不知道如何与右边的Point类相乘),Python将查看右边的对象,看看
__rmul_______________
定义了特殊的方法,它有效吗?如果是这样,它将使用这个实现。
对于可交换的类(即,可以将
B还是B
A)并得到相同的结果)您可以将其定义为:
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)
def __rmul__(self, other):
return self.__mul__(other)