MartinHaTh
MartinHaTh

Reputation: 1447

Python multiply int to instance both ways

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?

Upvotes: 6

Views: 2571

Answers (1)

Will
Will

Reputation: 75663

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.

Upvotes: 12

Related Questions