我以前从未处理过反向操作员,所以请不要燃烧!刚刚完成了解它们,所以想尝试一下.但由于某种原因,它不起作用.这是代码:
>>> class Subtract(object):
def __init__(self, number):
self.number = number
def __rsub__(self, other):
return self.number - other.number
>>> x = Subtract(5)
>>> y = Subtract(10)
>>> x - y # FAILS!
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
x - y
TypeError: unsupported operand type(s) for -: 'Subtract' and 'Subtract'
>>> x.__rsub__(y) # WORKS!
-5
Run Code Online (Sandbox Code Playgroud)
如果我改变__rsub__到__sub__,它的工作原理.
我究竟做错了什么?这些反向运营商的目的是什么?