4

Ok, so I'm creating a Vector class (the mathematical vector, like [1,3]), and I want to multiply an instance of Vector with an int. First, I implemented the __mul__ method, and it works fine. However, this don't quite solves the problem.

a = Vector(4,3)  # Creates a vector, [4,3]
a*4     # This works fine, and prints [16,12]
4*a     # This, however, creates a TypeError (Unsupported operans type(s)).

Now, this is useable, but it could be easier to have it work both ways. Is there a way to do this, in the Vector class?

Andrew Wilkinson
  • 10,682
  • 3
  • 35
  • 38
MartinHaTh
  • 1,417
  • 1
  • 13
  • 25
  • This is explained in [the documentation](http://docs.python.org/reference/datamodel.html#emulating-numeric-types). – Björn Pollex Nov 22 '11 at 10:58
  • This has been solved in another post. [http://stackoverflow.com/questions/6892616/python-multiplication-override][1] [1]: http://stackoverflow.com/questions/6892616/python-multiplication-override – Eduardo Jun 17 '13 at 20:22

1 Answers1

10

your Vector class can provide the __rmul__() reflected multiply method, which is the method used to implement multiplication when the left-hand operand does not support the operation.

Will
  • 73,905
  • 40
  • 169
  • 246