類別繼承

Python 物件導向程式設計

Alex Yarosh

Content Quality Analyst @ DataCamp

程式碼重用

Python 物件導向程式設計

程式碼重用

 

1. 別人已經做過了

 

  • 模組適合固定功能
  • OOP 適合自訂功能

多個 Python 套件的標誌

Python 物件導向程式設計

程式碼重用

 

1. 別人已經做過了

 

2. DRY:Don't Repeat Yourself(勿重複)

各式 GUI 元件

Python 物件導向程式設計

程式碼重用

 

1. 別人已經做過了

 

2. DRY:Don't Repeat Yourself(勿重複)

不要重複各種 GUI 元件

Python 物件導向程式設計

繼承

 

$$\Large{\text{新類別功能 = 舊類別功能 + 額外功能}}$$

Python 物件導向程式設計

帳戶類別

Python 物件導向程式設計

從帳戶繼承的儲蓄帳戶

Python 物件導向程式設計

兩個類別從帳戶繼承

Python 物件導向程式設計

在支票帳戶中修改的方法

Python 物件導向程式設計

實作類別繼承

class BankAccount:
    def __init__(self, balance):
       self.balance = balance

    def withdraw(self, amount):
        self.balance -= amount

# Empty class inherited from BankAccount
class SavingsAccount(BankAccount):
    pass

class MyChild(MyParent):
   # Do stuff here
  • MyParent:被擴充/被繼承功能的類別
  • MyChild:會繼承並加入更多功能的類別
Python 物件導向程式設計

子類別擁有父類別的所有資料

# Constructor inherited from BankAccount
savings_acct = SavingsAccount(1000)
type(savings_acct)
__main__.SavingsAccount
# Attribute inherited from BankAccount
savings_acct.balance
1000
# Method inherited from BankAccount
savings_acct.withdraw(300)
Python 物件導向程式設計

繼承:「is-a」關係

SavingsAccount 是一種 BankAccount

(可能含有特殊功能)

savings_acct = SavingsAccount(1000)
isinstance(savings_acct, SavingsAccount)
True
isinstance(savings_acct, BankAccount)
True

 

 

acct = BankAccount(500)
isinstance(acct,SavingsAccount)
False
isinstance(acct,BankAccount)
True
Python 物件導向程式設計

一起來練習吧!

Python 物件導向程式設計

Preparing Video For Download...