小编Ran*_*dy 的帖子

在Python中使用反向运算符

我以前从未处理过反向操作员,所以请不要燃烧!刚刚完成了解它们,所以想尝试一下.但由于某种原因,它不起作用.这是代码:

>>> 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__,它的工作原理.

我究竟做错了什么?这些反向运营商的目的是什么?

python operators

8
推荐指数
2
解决办法
4155
查看次数

标签 统计

operators ×1

python ×1