3

とても簡単なことのように感じますが、必要な情報が見つからないようです。クラス Matrix を定義するとします。

class Matrix():
    def __mul__(self, other):
    if isinstance(other, Matrix):
        #Matrix multiplication.
    if isinstance(other, int): #or float, or whatever
        #Matrix multiplied cell by cell.

これは、行列に int を掛けると問題なく動作しますが、int は行列の処理方法を認識していないため、3*Matrix は TypeError を発生させます。どうすればこれに対処できますか?

4

2 に答える 2

4

のメソッド__rmul__の呼び出しをオーバーライドするように定義します。int()__mul__

class Matrix():
    # code

    def __rmul__(self, other):
        #define right multiplication here.

        #As Ignacio said, this is the ideal
        #place to define matrix-matrix multiplication as __rmul__() will
        #override __mul__().

    # code

これはすべての数値演算子で実行できることに注意してください。

また、新しいスタイル クラスを使用することをお勧めします。そのため、クラスを次のように定義します。

class Matrix(object):

これにより、次のようなことが可能になります。

if type(other) == Matrix: ...
于 2012-06-01T18:27:27.827 に答える
1

メソッドも定義__rmul__()します。

于 2012-06-01T18:27:14.023 に答える