4

I am not sure what to call this so please bear with me.

Right now I have a class / object where I overloaded the multiplication operator def __mul__(self, secondthing):and so if I do myObject * 4 it knows what to do with it.

But it doesn't know what to do if I do 4 * myObject, the other way around.

DoubleBass
  • 1,143
  • 4
  • 12
  • 29
  • 3
    See https://docs.python.org/2/reference/datamodel.html#object.__rmul__ - *"These functions are only called if the left operand does not support the corresponding operation and the operands are of different types."* – jonrsharpe Apr 10 '15 at 13:17
  • http://stackoverflow.com/questions/6892616/python-multiplication-override – NKamrath Apr 10 '15 at 13:18

1 Answers1

2

You could implement __rmul__.

These methods are called to implement the binary arithmetic operations (+, -, *, /, %, divmod(), pow(), **, <<, >>, &, ^, |) 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.

Kevin
  • 74,910
  • 12
  • 133
  • 166
  • [this](http://stackoverflow.com/a/6892635/953482) related posts suggests that you can just do `__rmul__ = __mul__`, provided the implementations would have been identical anyway. – Kevin Apr 10 '15 at 13:21
  • Always try to be [DRY](http://en.m.wikipedia.org/wiki/Don%27t_repeat_yourself). Create another function and call it in both or possibly call the other overload function directly. – Paul Rooney Apr 10 '15 at 13:22