我試圖學習如何在 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
uj5u.com熱心網友回復:
你有一個小錯字( 應該是 a *)。
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/474875.html
下一篇:無法將'LinkedList::filter(void(*)(Node*))::<lambda(Node*)>'轉換為'void(*)(Node*)'
