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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With