Python: rtruediv not working as I expect

Using V3 python, I create:

class NewInt(int):
  def __rtruediv__(self, num):
    print('in here')

x = NewInt(5)

343 / x    # called rtruediv as I expect, but

343.3 / x  # does not call rtruediv

I don’t know why this is happening because:

x / 343
x / 343.3   #both will call truediv

To me, this seems inconsistent.

Does anyone have an explanation why this is so .. and when Python does 343.3 / x there is a method that can be overridden?

I found this behavior while looking at some overload information and came across this inconsistency.

Dave

+4
source share
2 answers

In short, the left operand receives the first shot when processing the operation, except in some special circumstances.

The relevant documentation here is in emulating numeric types :

: , . .

:

343.3 / x  # does not call __rtruediv__

, float int , NewInt n int. 343.3.__truediv__(x) .

, , :

343 / x     # x.__rtruediv__ wins because NewInt subclasses int
343.3 / x   # 343.3.__truediv__ wins because NewInt does not subclass float
x / 343     # x.__truediv__ wins because int does not subclass NewInt
x / 343.3   # x.__truediv__ wins because float does not subclass NewInt
+4

__rtruediv__ __truediv__, .

343 / x, NewInt int, x __rtruediv__ . 343.3 / x, NewInt float, 343.3 __truediv__ .

343.3.__truediv__(x) NotImplemented, float , float int. , x.__rtruediv__ .

+3

All Articles