Python中的重载运算符__mul__

4
我正在尝试在这个例子中实现__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个回答

6
为此,您需要使用__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.

在这种情况下,只需在类定义中添加__rmul__ = __mul__即可(当然,在__mul__之后 :-))。 - mgilson
@mgilson 非常好的观点 - 非常感谢。 (我必须承认,我没有考虑实现,只是如何调用该方法)。 - Ami Tavory

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接