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?
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).
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”).
__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.
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 == .
Just add the following to the class definition and you should be good to go:
__rmul__ = __mul__
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With