Python 中的乘法运算符就是计算标量积(scalar product),也叫元素级乘法 (elementwise multipication)
如下:
def __mul__(self, scalar):
if isinstance(scalar, numbers.Real):
return Vector(n * scalar for n in self)
else:
return NotImplemented
def __rmul__(self, scalar):
return self * scalar
涉及 Vector 操作数的积还有一种,叫两个向量的点积(dot product),如果把一个向量看做 1xN 矩阵,把另一个向量看做 Nx1 矩阵,那么就是矩阵乘法。在 numpy 中,点积使用 numpy.dot()函数计算。
如下:
def __matmul__(self, other):
try:
return sum(a * b for a, b in zip(self, other))
except TypeError:
return NotImplemented
def __rmatmul__(self, other):
return self @ other # this only works in Python 3.5