问题描述
当我从整数中减去浮点数时(例如 1-2.0),Python 会进行隐式类型转换(我认为).但是当我使用魔术方法 __sub__ 调用我认为是相同的操作时,它突然不再存在了.
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 using the magic method __sub__, it suddenly does not anymore.
我在这里缺少什么?当我为自己的类重载运算符时,除了将输入显式转换为我需要的任何类型之外,还有其他方法吗?
What am I missing here? When I overload operators for my own classes, is there a way around this other than explicitly casting input to whatever type I need?
a=1 a.__sub__(2.) # returns NotImplemented a.__rsub__(2.) # returns NotImplemented # yet, of course: a-2. # returns -1.0
推荐答案
a - b 不仅仅是 a.__sub__(b).如果 a 无法处理该操作,它也会尝试 b.__rsub__(a),在 1 - 2. 的情况下,它是float 的 __rsub__ 处理操作.
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
您运行了 a.__rsub__(2.),但这是错误的 __rsub__.您需要右侧操作数的 __rsub__,而不是左侧操作数.
You ran a.__rsub__(2.), but that's the wrong __rsub__. You need the right-side operand's __rsub__, not the left-side operand.
减法运算符没有内置隐式类型转换.float.__rsub__ 必须手动处理整数.如果您想在自己的运算符实现中进行类型转换,您也必须手动处理.
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.