我正在尝试使用大多数正常的数学运算来构建矩阵的类表示.我用标量乘法运算遇到了麻烦.
代码的相关部分如下:
import numpy
class Matrix(object):
def __init__(self, array):
self.array = numpy.array(array, dtype=int)
def __mul__(self, other):
if type(other) == int:
return Matrix(other*self.array)
else:
raise ValueError("Can not multiply a matrix with {0}".format(type(other)))
Run Code Online (Sandbox Code Playgroud)
标量乘法表示的标准方法是cA,其中c是标量,A是矩阵,因此c*A在Python中.但是,这会因为预期的运行TypeError: unsupported operand type(s) for *: 'int' and 'Matrix'而失败A*c(请注意other*self.array).因此我得出结论,*操作数是为int和定义的numpy.array.
这是什么魔法,我怎样才能复制这种行为?
你需要一个__rmul__你的头脑.例如,如果添加
def __rmul__(self, other):
return self.__mul__(other)
Run Code Online (Sandbox Code Playgroud)
然后:
>>> A = Matrix(np.arange(12).reshape(3, 4))
>>> (2 * A).array
array([[ 0, 2, 4, 6],
[ 8, 10, 12, 14],
[16, 18, 20, 22]])
Run Code Online (Sandbox Code Playgroud)
就像在文档中一样__r***__
被调用以实现具有反射(交换)操作数的二进制算术运算.仅当左操作数不支持相应操作且操作数具有不同类型时才调用这些函数.
| 归档时间: |
|
| 查看次数: |
28 次 |
| 最近记录: |