Создала класс Fraction, не могу понять, где ошибка в коде. Необходимо сложить дробь и целое число? Пожалуйста, помогите разобраться!
def gcd(a,b):
while a%b != 0:
olda = a
oldb = b
a = oldb
b = olda%oldb
return b
class Fraction:
def __init__(self,a,b):
self.num = a
self.den = b
def __str__(self):
return str(self.num)+"/"+str(self.den)
def show(self):
print(self.num,"/",self.den)
def __add__(self,otherfraction):
if not isinstance(self, Fraction):
return NotImplemented
if isinstance(otherfraction, Fraction):
self.num = otherfraction.num
self.den = otherfraction.den
elif isinstance(otherfraction, int):
self.num = otherfraction
self.den = 1
else:
return NotImplemented
newnum = self.num*otherfraction.den + \
self.den*otherfraction.num
newden = self.den * otherfraction.den
common = gcd(newnum,newden)
return Fraction(newnum//common,newden//common)
print(Fraction(3,5)+3)
Со сложением дроби и дроби код работает:
def gcd(a,b):
while a%b != 0:
olda = a
oldb = b
a = oldb
b = olda%oldb
return b
class Fraction:
def __init__(self,a,b):
self.num = a
self.den = b
def __str__(self):
return str(self.num)+"/"+str(self.den)
def show(self):
print(self.num,"/",self.den)
def __add__(self,otherfraction):
newnum = self.num*otherfraction.den + \
self.den*otherfraction.num
newden = self.den * otherfraction.den
common = gcd(newnum,newden)
return Fraction(newnum//common,newden//common)
x = Fraction(1,2)
y = Fraction(1,2)
print(x+y)