为什么我的add函数没有给我正确的输出?



我试图学习如何在python中创建类,我编写了以下代码来创建一个名为fraction的类。然而,当我尝试将两个分数相加时,我没有得到正确的输出。谁能告诉我我哪里做错了?

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)

分数我试图添加的是1/4和2/4

print(fraction(1,4)+fraction(2,4))

输出我得到:10/16

期望输出:12/16

您有一个小错别字(+应该是*)

class Fraction:
def __init__(self, top, bottom):
self.num = top
self.den = bottom
def show(self):
print(self)  # this automatically calls self.__str__()!
def __str__(self):
return f"{self.num}/{self.den}"

def __add__(self, other):
new_num = self.num * other.den + other.num * self.den
new_den = self.den * other.den
return Fraction(new_num, new_den)
(Fraction(1, 4) + Fraction(2, 4)).show()  # 12/16

最新更新