[英]Why and when do literal comparison operators like `==` in Python use the magic method of a custom type over a builtin?
[英]Why does calling Python's 'magic method' not do type conversion like it would for the corresponding operator?
当我从一个整数中减去一个浮点数(例如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)
。 如果a
无法处理操作,它也会尝试b.__rsub__(a)
,而在1 - 2.
情况下,它是float的__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
了TypeError
。
最后,
a1 - b
A.__sub__
# TypeError: unsupported operand type(s) for -: 'A' and 'B'
这次,首先尝试a1.__sub__
,返回NotImplemented
。 现在,由于未定义b.__rsub__
,因此引发了TypeError
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.