開始使用免費開始

在繼承的類別中新增方法

讓我們在 MortgageCalculator 中新增一個方法,用來根據本金、年利率,以及還款年數來計算每月還款金額。

本練習屬於課程

案例研究:用 Python 建構軟體

檢視課程

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

class MortgageCalculator(FinancialCalculator):
  def __init__(self, loan_amount, annual_interest_rate, years):
    super().__init__()
    self.loan_amount = loan_amount
    self.monthly_interest_rate = self.monthly_interest(annual_interest_rate)
    self.months = self.multiply(years, 12)
    self.monthly_payment = self.calculate_monthly_payment()
  
  def calculate_monthly_payment(self):
    numerator = self.monthly_interest_rate * (1 + self.monthly_interest_rate) ** self.months
    denominator = (1 + self.monthly_interest_rate) ** self.months - 1
    
    # Compute the quotient of numerator and denominator and save the result to multiplier
    multiplier = self.divide(____, ____)
編輯並執行程式碼