4

i'm trying to implement __mul__ on this example

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'

however it does not work at 50 * f1.

Does anyone know how to solve it?

Bolor
  • 413
  • 6
  • 14

1 Answers1

6

For this you need the __rmul__ method:

These methods are called to implement the binary arithmetic operations (+, -, *, /, %, divmod(), pow(), **, <<, >>, &, ^, |) with reflected (swapped) operands.

In your case:

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.
Ami Tavory
  • 74,578
  • 11
  • 141
  • 185
  • In this case, it's easy enough to just add `__rmul__ = __mul__` to the class definition (after `__mul__` of course :-) – mgilson Aug 18 '16 at 23:51
  • @mgilson That's an excellent point - many thanks. (I must confess I didn't get to think of the implementation, just how to get the method called). – Ami Tavory Aug 18 '16 at 23:53