Search code examples
pythonmathfractionsmagic-methods

__rsub__ and __rtruediv__ with fractions


I'm attempting to use the __rsub__ function in a class I've made called Fraction.

Here's the Fraction class code:

def __init__(self, num, denom):
    ''' Creates a new Fraction object num/denom'''
    self.num = num
    self.denom = denom
    self.reduce()

def __repr__(self):
    ''' returns string representation of our fraction'''
    return str(self.num) + "/" + str(self.denom)

def reduce(self):
    ''' converts our fractional representation into reduced form'''
    divisor = gcd(self.num, self.denom)
    self.num = self.num // divisor
    self.denom = self.denom // divisor
def __sub__(self, other):
    if isinstance(other,Fraction) == True:
        newnum = self.num * other.denom - self.denom*other.num
        newdenom = self.denom * other.denom
        return Fraction(newnum, newdenom)

Now if I do __radd__ or __rmul__ by using: return self + other or return self * other respectively, it will perform the desired result. However, doing __rsub__ and __rtruediv__ do not work by simply changing the operator. How can I fix this?

Essentially, the code calling the functions is:

f = Fraction(2,3)
g = Fraction(4,8)
print("2 - f: ", 2 - f)
print("2 / f: ", 2 / f)

Thanks for any help!


Solution

  • You first need to convert other to a Fraction to make this work:

    def __rsub__(self, other):
        return Fraction(other, 1) - self
    

    Since __rsub__() only gets called if other is not of type Fraction, we don't need any type checking -- we simply assume it is an integer.

    Your current implementation of __sub__() also needs some work -- it returns nothing if other does not have the type Fraction.