Reputation: 75
Let's say I want to define a class with a __mul__
method, for example:
class A():
def __init__(self,*arg,**kwarg):
#some code
def __mul__(self,other):
#some code
If I do A()*2
it will give me a result. But when I try the other way around (2*A()
), it doesn't work.
Is there a way to implement this other way around operation?
Upvotes: 3
Views: 53
Reputation: 36682
You would use object.__rmul__(self, other)
:
class A():
def __init__(self, *arg, **kwarg):
#some code
def __mul__(self, other):
#some code
def __rmul__(self, other):
return self * other
https://docs.python.org/3/reference/datamodel.html
Upvotes: 5