Code:
class Vector:
def __init__(self):
self.x = 0.0
self.y = 0.0
def __mul__(self, scalar):
v = Vector()
v.x = self.x * scalar
v.y = self.y * scalar
return v
v = Vector()
v.x = 2
v.y = 5
v = v * 2
Question: is there a way to overload mul operator in a way that this becomes possible:
v = 2 * v
?
Use __rmul__
:
def __rmul__(self, scalar): # self: right operand (Vector)
v = Vector()
v.x = self.x * scalar
v.y = self.y * scalar
return v
__rmul__
called when the left-hand operand does not support the corresponding operation ( __mul__
).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.