Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a Python class apply two-way overloading? [duplicate]

Tags:

python

class

I am not sure what to call this so please bear with me.

Right now I have a class / object where I overloaded the multiplication operator def __mul__(self, secondthing):and so if I do myObject * 4 it knows what to do with it.

But it doesn't know what to do if I do 4 * myObject, the other way around.

like image 411
DoubleBass Avatar asked Jul 20 '26 17:07

DoubleBass


1 Answers

You could implement __rmul__.

These methods are called to implement the binary arithmetic operations (+, -, *, /, %, divmod(), pow(), **, <<, >>, &, ^, |) with reflected (swapped) operands. These functions are only called if the left operand does not support the corresponding operation and the operands are of different types.

like image 195
Kevin Avatar answered Jul 23 '26 06:07

Kevin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!