当我从一个整数中减去一个浮点数(例如1-2.0
)时,Python会进行隐式类型转换(我认为)。但是当我使用魔法__sub__
调用我认为是相同的操作时,它突然不再了。
我在这里错过了什么?当我为自己的类重载运算符时,除了明确地将输入转换为我需要的任何类型之外,还有其他方法吗?
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)
。它还尝试b.__rsub__(a)
如果a
无法处理操作,并且在1 - 2.
情况下,它是浮动的__rsub__
处理操作。
>>> (2.).__rsub__(1)
-1.0
你跑a.__rsub__(2.)
,但这是错误的__rsub__
。你需要右侧操作数的__rsub__
,而不是左侧操作数。
减法运算符中没有内置的隐式类型转换。 float.__rsub__
必须手动处理。如果您想在自己的运算符实现中进行类型转换,那么您也必须手动处理它。
@ user2357112已经说得很好,但没有什么比如一个例子了。
class A:
def __sub__(self, other):
print('A.__sub__')
if not isinstance(other, A):
return NotImplemented
return 0
def __rsub__(self, other):
print('A.__rsub__')
if not isinstance(other, A):
return NotImplemented
return 0
class B:
def __sub__(self, other):
print('B.__sub__')
if not isinstance(other, B):
return NotImplemented
return 0
a1 = A()
a2 = A()
b = B()
a1 - a2
A.__sub__
# 0
对象a1
和a2
兼容(两种类型A
),返回有效结果。
接下来考虑,
b - a1
B.__sub__
A.__rsub__
# TypeError: unsupported operand type(s) for -: 'B' and 'A'
对象b
和a1
不兼容。首先,尝试b.__sub__
,返回NotImplemented
,所以尝试a1.__rsub__
,这也返回NotImplemented
。所以提出了一个TypeError
。
最后,
a1 - b
A.__sub__
# TypeError: unsupported operand type(s) for -: 'A' and 'B'
这一次,首先尝试a1.__sub__
,返回NotImplemented
。现在,由于没有定义b.__rsub__
,因此提出了TypeError
。