Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 225
MartinHaTh Avatar asked Feb 23 '23 08:02

MartinHaTh


1 Answers

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.

like image 53
Will Avatar answered Feb 27 '23 02:02

Will