問題描述
當我從整數中減去浮點數時(例如 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.
這篇關于為什么調用 Python 的“魔術方法"不像對應的運算符那樣進行類型轉換?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!