2

I created a class called Rational - which represents a rational number - with a method that allows it to be added to another Rational object, but am having a hard time figuring out a way to allow it to be added to an integer object through a method inside the Rational class.

# This already works
a = Rational(1,2);
b = Rational(1,1)  
# a+b -> 3/2

# This is what I wish also worked
a+1 = 3/2

The code I have:

class Rational:

    def __init__(self,num:int,den:int=1):
        self.num = num
        self.den = den
        try:
            value = self.num/self.den
        except:
            print("O denominador não pode ser 0.")
            
            
    def __str__(self):
        if self.den == 1:
            return f"{self.num}"
        elif self.den > 0:
            return f"{self.num}/{self.den}"
        elif self.den < 0:
            return f"{-self.num}/{-self.den}"
       
        
    def __add__(self, other):
        if self.den != other.den:
            num_new = (self.num*other.den) + (other.num*self.den)
            den_new = self.den*other.den
        else:
            num_new = self.num + other.num
            den_new = self.den
        return Rational(num_new,den_new)

Is there a simple way to make this happen?

anon01
  • 10,618
  • 8
  • 35
  • 58

0 Answers0