I’m trying to make a class A that supports both multiplication between two instances of A and scalar multiplication.
I currently have the following implementation for the __mul__ method:
class A:
def __init__(self, value: float):
self.value = value
def __mul__(self, other):
if type(other) == A:
return A(self.value * other.value)
elif type(other) == float:
return A(other * self.value)
else:
raise
This allows to perform multiplication x * y where x is an instance of A and y is an intance of A or float. However if x is a float and y in an A then a TypeError is raised.
Is there a way to overload this case as well? If it matters, I would like the same behaviour regardless of whether the instance of A is the left or right operand.
>Solution :
Add __rmul__:
class A:
...
__rmul__ = __mul__