Why does calling Python's 'magic method' not do type conversion like it would for the corresponding operator?

前端 未结 2 614
甜味超标
甜味超标 2021-01-03 18:45

When I subtract a float from an integer (e.g. 1-2.0), Python does implicit type conversion (I think). But when I call what I thought was the same operation usin

2条回答
  •  無奈伤痛
    2021-01-03 19:13

    a - b isn't just a.__sub__(b). It also tries b.__rsub__(a) if a can't handle the operation, and in the 1 - 2. case, it's the float's __rsub__ that handles the operation.

    >>> (2.).__rsub__(1)
    -1.0
    

    You ran a.__rsub__(2.), but that's the wrong __rsub__. You need the right-side operand's __rsub__, not the left-side operand.


    There is no implicit type conversion built into the subtraction operator. float.__rsub__ has to handle ints manually. If you want type conversion in your own operator implementations, you'll have to handle that manually too.

提交回复
热议问题