为什么我的添加功能没有给我正确的输出?

Why is my add function not giving me the correct output?

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

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