Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: multiplication override

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?

like image 445
Colin DeClue Avatar asked Jul 31 '11 22:07

Colin DeClue


People also ask

How do you overload multiplication in Python?

Overriding the multiply operator If you look at __mul__ , you will see that the first thing we do is to check if other is a scalar. We do this by checking if it is an instance of int or float (you could also check complex if you wanted the Matrix class to support complex number, but we won't bother in this example).

What is __ MUL __ in Python?

The Python __mul__() method is called to implement the arithmetic multiplication operation * . For example to evaluate the expression x * y , Python attempts to call x. __mul__(y) . We call this a “Dunder Method” for “Double Underscore Method” (also called “magic method”).

What is __ add __ in Python?

__add__ magic method is used to add the attributes of the class instance. For example, let's say object1 is an instance of a class A and object2 is an instance of class B and both of these classes have an attribute called 'a', that holds an integer.

How do you overload the operator in Python?

In Python, overloading is achieved by overriding the method which is specifically for that operator, in the user-defined class. For example, __add__(self, x) is a method reserved for overloading + operator, and __eq__(self, x) is for overloading == .


1 Answers

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

__rmul__ = __mul__ 
like image 115
Karl Knechtel Avatar answered Oct 13 '22 00:10

Karl Knechtel