開始使用免費開始

從零開始建立類別

在本章最後一個練習中,你將扮演 Python 開發者,從零開始建立自己的類別,包含建構子!

你會設計一個 Calculator 類別,並加入可對兩個數值進行加法、減法與乘法的各種方法。

本練習屬於課程

Python 物件導向程式設計入門

檢視課程

練習說明

  • 定義一個 Calculator 類別,初始化時帶入兩個參數:num_onenum_two
  • 定義 addition() 方法,回傳 self.num_one 加上 num_two
  • 定義 subtraction() 方法,回傳 self.num_one 減去 num_two
  • 定義 multiplication() 方法,回傳 self.num_one 乘以 num_two

動手互動練習

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

# Define and initialize the Calculator class
____:
  ____ ____(____, ____, ____):
    self.____ = ____
    self.____ = ____
  
  # Create the addition method
  def ____(____):
    return self.____ ____ self.____
  
  # Create the subtraction method
  def ____(____):
    return ____
  
  # Create the multiplication method
  def ____(____):
    ____   
編輯並執行程式碼