Python: multiplication override

PythonOverridingOperator Keyword

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

Just add the following to the class definition and you should be good to go:

__rmul__ = __mul__

Solution 2 - Python

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__

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionColin DeClueView Question on Stackoverflow
Solution 1 - PythonKarl KnechtelView Answer on Stackoverflow
Solution 2 - PythonCat Plus PlusView Answer on Stackoverflow