So, I've got a custom class that has a __mul__ function which works with ints. However, in my program (in libraries), it's getting called the other way around, i.e., 2 * x where x is of my class. Is there a way I can have it use my __mul__ function for this?
            Asked
            
        
        
            Active
            
        
            Viewed 5.1k times
        
    53
            
            
         
    
    
        Colin DeClue
        
- 2,194
- 3
- 26
- 47
2 Answers
60
            Just add the following to the class definition and you should be good to go:
__rmul__ = __mul__
 
    
    
        Karl Knechtel
        
- 62,466
- 11
- 102
- 153
- 
                    8Note that this won't always be what you want. Suppose you have vector and matrix classes, and you want to define multiplication between them by treating the vector as a 1xN matrix. Matrix multiplication isn't commutative, so you'd need to re-switch the order of arguments. – Karl Knechtel Aug 01 '11 at 04:24
37
            
            
        Implement __rmul__ as well.
class Foo(object):
    def __mul__(self, other):
        print '__mul__'
        return other
    def __rmul__(self, other):
        print '__rmul__'
        return other
x = Foo()
2 * x # __rmul__
x * 2 # __mul__
 
    
    
        Cat Plus Plus
        
- 125,936
- 27
- 200
- 224
- 
                    1
- 
                    @Pi also overload `__repr__`. See https://stackoverflow.com/questions/1535327. – Karl Knechtel Apr 15 '23 at 05:35