從零開始建立類別
在本章最後一個練習中,你將扮演 Python 開發者,從零開始建立自己的類別,包含建構子!
你會設計一個 Calculator 類別,並加入可對兩個數值進行加法、減法與乘法的各種方法。
本練習屬於課程
Python 物件導向程式設計入門
練習說明
- 定義一個
Calculator類別,初始化時帶入兩個參數:num_one與num_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 ____(____):
____