I am trying to define a class Fraction:
def __init__(self,num=0,denom=1):
self.num = num
self.denom = denom
And I also want to define a add method,
def __add__(self,right):
if type(right) is int:
return (self.num/self.denom) + right
if type(right) is Fraction:
return ((self.num/self.denom)+(right.num/right.denom))
def __radd__(self,left):
return (self.num/self.denom)+left
It works, and always returns a float. However, I want it to return a fraction. For example: if I test:
f = Frac(1,2)
f + Frac(1,3)
f + 2
Frac(1,3) + f
2 + f
I always get:
*Error: f+Frac(1,3) -> 0.8333333333333333 but should -> 5/6
*Error: f+2 -> 2.5 but should -> 5/2
*Error: Frac(1,3)+f -> 0.8333333333333333 but should -> 5/6
*Error: 2+f -> 2.5 but should -> 5/2
Are there any methods that can convert the result from a float to a fraction? Thank you so much.