为什么调用Python的“魔术方法”不像对应的运算符那样进行类型转换?

问题描述 投票:30回答:2

当我从一个整数中减去一个浮点数(例如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
python type-conversion implicit-conversion magic-methods
2个回答
38
投票

a - b不仅仅是a.__sub__(b)。它还尝试b.__rsub__(a)如果a无法处理操作,并且在1 - 2.情况下,它是浮动的__rsub__处理操作。

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

你跑a.__rsub__(2.),但这是错误的__rsub__。你需要右侧操作数的__rsub__,而不是左侧操作数。


减法运算符中没有内置的隐式类型转换。 float.__rsub__必须手动处理。如果您想在自己的运算符实现中进行类型转换,那么您也必须手动处理它。


8
投票

@ 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

对象a1a2兼容(两种类型A),返回有效结果。

接下来考虑,

b - a1
B.__sub__
A.__rsub__
# TypeError: unsupported operand type(s) for -: 'B' and 'A'

对象ba1不兼容。首先,尝试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

© www.soinside.com 2019 - 2024. All rights reserved.