1

I'm implementing a Fraction class to work with fractions (although python have a library for this), well the problem is, I can use the __add__ (+) operator between a fraction and an integer, but I can't use __add__ between an integer and a fraction. When the expression's order changes, I get an error.

>>> 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'
>>> 

Is there a way to make this expression 1 + Fraction(1, 2) work? Perhaps a left __add__ operator for the Fraction class?

1
  • 4
    __radd__ Commented Apr 7, 2021 at 8:51

1 Answer 1

1

Just implement radd mirroring add.

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)
Sign up to request clarification or add additional context in comments.

Comments