0

How is the operator overloading parsed? I have a class object o and want to do -1 * o with the overloaded __mul__ operator. Would that be parsed correctly when the left operand is a -1? Multiplication should be commutative (except for matrices and cross-products)... ?

4
  • 1
    FYI: Multiplication is overloaded by defining __mul__, not __mult__. Commented Oct 6, 2014 at 18:05
  • Did you read the documentation, which describes separate methods for customizing left- and right-hand operations? Commented Oct 6, 2014 at 18:06
  • Not all multiplication is commutative. Matrix multiplication, for instance. That's why there's separate left and right multiplication operators. Commented Oct 6, 2014 at 18:11
  • Yes matrix or vector vector mult is not. I was looking at scalar - vector products in my case. Commented Oct 6, 2014 at 18:17

2 Answers 2

6

That's what __rmul__ is for. In your scenario, Python calls int.__mul__(-1, o). int doesn't know how to do this operation, so this call returns NotImplemented. Python therefore calls type(o).__rmul__(o, -1) giving your class the chance to handle it.

Sign up to request clarification or add additional context in comments.

Comments

-1

Operators are always parsed the same way regardless of overloading. Because unary - has higher precedence than *, -1 * o will always be parsed as (-1) * o.

1 Comment

I don't think that is what the OP is getting at, although his use of "parsing" may misleadingly suggest it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.