重载运算符__mul__ python

时间:2016-08-18 23:44:20

标签: python oop numpy operator-overloading

我正在尝试在此示例中实现__mul__

class foo:
    def __init__(self, data):
        self.data = data
    def __mul__(self, other):
        if type(other) in (int, float):
            return foo(self.data * other)
        else:
            return foo(self.data * other.data)

if __name__ == '__main__':
   f1 = foo(10)
   f2 = foo(20)

   (f1*f2).data # 200
   (f1*50).data # 500
   (50*f1).data # TypeError: unsupported operand type(s) for *: 'int' and 'instance'

然而它在50 * f1无效。

有谁知道如何解决它?

1 个答案:

答案 0 :(得分:4)

为此,您需要__rmul__方法:

  

调用这些方法来实现二进制算术运算(+, - ,*,/,%,divmod(),pow(),**,<<,>>,&,^, |)与反射(交换)操作数。

在你的情况下:

class foo:
    def __init__(self, data):
        self.data = data

    def __mul__(self, other):
        # As before

    def __rmul__(self, other):
        # This will be called in the situation you brought up.