首页 > 解决方案 > Python 重载运算符不能在表达式的“两侧”工作

问题描述

我正在实现一个Fraction使用分数的类(尽管python为此提供了一个库),问题是,我可以__add__在分数和整数之间使用(+)运算符,但我不能__add__在整数和整数之间使用一小部分。当表达式的顺序改变时,我得到一个错误。

>>> a = Fraction(1, 2)
>>> a + 1
Fraction(numerator=3.0, denominator=2)
>>> 1 + a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'Fraction'
>>> 

有没有办法使这种表达方式1 + Fraction(1, 2)起作用?也许类的左__add__运算符Fraction

标签: pythonpython-3.xclassoop

解决方案


只需实现radd镜像添加。

class Fraction:
    def __init__(self, value):
        self.value = value

    def __add__(self, other):
        return Fraction(self.value+other)

    def __radd__(self, other):
        return self.__add__(other)


if __name__ == "__main__":
    print((Fraction(1)+1).value)
    print((1+Fraction(1)).value)

推荐阅读