I was trying to learn how to create classes in python and I wrote the following code to create a class called fraction. However, when I try to add two fractions, I don't get the correct output. Can someone tell me where I might have gone wrong?
class fraction:
def __init__(self,top,bottom):
self.num=top
self.den=bottom
def show(self):
print(f"{self.num}/{self.den}")
def __str__(self):
return f"{self.num}/{self.den}"
def __add__(self,other_fraction):
new_num=self.num*other_fraction.den+self.den+other_fraction.num
new_den=self.den*other_fraction.den
return fraction(new_num,new_den)
Fraction I tried to add are 1/4 and 2/4
print(fraction(1,4)+fraction(2,4))
Output I got:
10/16
Expected output:12/16