Python 物件導向程式設計
Alex Yarosh
Content Quality Analyst @ DataCamp

# Withdraw amount from each of accounts in list_of_accounts def batch_withdraw(list_of_accounts, amount): for acct in list_of_accounts: acct.withdraw(amount)b, c, s = BankAccount(1000), CheckingAccount(2000), SavingsAccount(3000) batch_withdraw([b,c,s]) # <-- Will use BankAccount.withdraw(), # then CheckingAccount.withdraw(), # then SavingsAccount.withdraw()
batch_withdraw() 不需檢查物件型別就知道要呼叫哪個 withdraw()
基底類別應可與其任何子類別互換,而不改變程式的任何性質
只要 BankAccount 可行,CheckingAccount 也應可行

基底類別應可與其任何子類別互換,而不改變程式的任何性質
→ 語法不相容
BankAccount.withdraw() 需要 1 個參數,但 CheckingAccount.withdraw() 需要 2 個
→ 子類別加強輸入條件
BankAccount.withdraw() 接受任意金額,但 CheckingAccount.withdraw() 假設金額受限
→ 子類別削弱輸出條件
BankAccount.withdraw() 只能留下正餘額或拋出錯誤,CheckingAccount.withdraw() 可能留下負餘額
→ 在子類別方法中變更額外屬性
→ 在子類別方法中額外拋出例外
$$\text{\textbf{\Huge{無 LSP——就無繼承}}}$$
Python 物件導向程式設計