Can a Python class apply two-way overloading? [dup

2020-04-11 16:50发布

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.

标签: python class
1条回答
等我变得足够好
2楼-- · 2020-04-11 17:33

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.

查看更多
登录 后发表回答