Leonardo Moraes
Leonardo Moraes

Reputation: 75

how do i implement a operation between built-in objects and created classes the other way around in python?

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

Answers (1)

Reblochon Masque
Reblochon Masque

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

Related Questions