開始使用免費開始

建立 Abstract Base Class

抽象基底類別能幫你為一組相當類似的類別建立「藍圖」。在這個練習中,你將建立一個名為 Company 的抽象基底類別,裡面包含一個抽象方法與一個具體方法。加油!

本練習屬於課程

Python 物件導向程式設計進階

檢視課程

練習說明

  • abc 模組匯入 ABCabstractmethod
  • 建立一個名為 Company 的抽象基底類別,並從 ABC 繼承。
  • 定義一個名為 create_budget() 的抽象方法,但使用 pass,不要實作任何邏輯。
  • 建立一個名為 hire_employee() 的具體方法。

動手互動練習

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

# Import the ABC class and abstractmethod decorator from abc
from abc import ____, ____

# Define an abstract base class called Company
class ____(____):
  # Create an abstract method called create_budget()
  ____
  def ____(self):
    ____
  
  # Create a concrete method with name hire_employee()
  def ____(self, name):
    print(f"Welcome to the team, {name}!")
編輯並執行程式碼