python - 复制 Python int * numpy.array 行为

标签 python numpy

我正在尝试构建包含大部分常规数学运算的矩阵的类表示。我在标量乘法运算中遇到了问题。

相关部分代码如下:

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)))

标量乘法的标准表示方式是 cA,其中 c 是标量,A 是矩阵,因此在 Python 中为 c*A。然而,这失败并出现 TypeError: unsupported operand type(s) for *: 'int' and 'Matrix'A*c 按预期运行(注意 other*self.array).因此我得出结论,* 操作数是为 intnumpy.array 定义的。

这是什么魔法?我该如何复制这种行为?

最佳答案

你需要一个 __rmul__在你的类(class)中。例如,如果您添加

def __rmul__(self, other):
    return self.__mul__(other)

然后:

>>> A = Matrix(np.arange(12).reshape(3, 4))
>>> (2 * A).array
array([[ 0,  2,  4,  6],
       [ 8, 10, 12, 14],
       [16, 18, 20, 22]])

docs , __r***__

are called to implement the binary arithmetic operations with reflected (swapped) operands. These functions are only called if the left operand does not support the corresponding operation and the operands are of different types.

关于python - 复制 Python int * numpy.array 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30287950/

相关文章:

Python动态数组分配,Matlab风格

python - 将双峰分布拟合到一组值

python - 渐近算法以外的算法的复杂性(Big-O - 表示法)

python - Flask-SQLAlchemy 数据类型

python - OpenCV TypeError : contour is not a numpy array, 既不是标量

python - 三维到二维

python - spark-submit 和 pyspark 有什么区别?

python - 找出对象的可能属性

python - python 的 numpy.ndarray 和 list 数据类型之间的区别

python - 查找数组中每个索引左侧/右侧的 Argmin