透過繼承客製化功能

Python 物件導向程式設計入門

George Boorman

Curriculum Manager, DataCamp

銀行帳戶類別的層級

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
Python 物件導向程式設計入門

自訂建構式

class SavingsAccount(BankAccount):    
    # Constructor for SavingsAccount with an additional argument
    def __init__(self, balance, interest_rate):  

# Call the parent constructor using ClassName.__init__() # self is a SavingsAccount but also a BankAccount BankAccount.__init__(self, balance)
# Add more functionality self.interest_rate = interest_rate
  • 可先用 Parent.__init__(self, args...) 執行父類別建構式
  • 加入更多功能
  • 不一定要呼叫父類別建構式
Python 物件導向程式設計入門

用自訂建構式建立物件

# Construct the object using the new constructor
acct = SavingsAccount(1000, 0.03)
acct.interest_rate
0.03
Python 物件導向程式設計入門

加入功能

  • 照常新增方法
  • 可同時使用父類別與子類別的資料
class SavingsAccount(BankAccount):
    def __init__(self, balance, interest_rate):
        BankAccount.__init__(self, balance)
        self.interest_rate = interest_rate

    # New functionality
    def compute_interest(self, n_periods=1):
        return self.balance * ( (1 + self.interest_rate) ** n_periods - 1)
Python 物件導向程式設計入門

銀行帳戶類別的層級

Python 物件導向程式設計入門

再加一個子類別

class CheckingAccount(BankAccount):

def __init__(self, balance, limit): BankAccount.__init__(self, balance) # Call the ParentClass constructor self.limit = limit
def deposit(self, amount): self.balance += amount
def withdraw(self, amount, fee=0): # New fee argument
if amount <= self.limit: BankAccount.withdraw(self, amount + fee) else: pass # Won't run if the condition isn't met
Python 物件導向程式設計入門
check_acct = CheckingAccount(1000, 25)

# Will call withdraw from CheckingAccount
check_acct.withdraw(200)

# Will call withdraw from CheckingAccount check_acct.withdraw(200, fee=15)
bank_acct = BankAccount(1000)

# Will call withdraw from BankAccount
bank_acct.withdraw(200)

# Will produce an error bank_acct.withdraw(200, fee=15)
TypeError: withdraw() got an unexpected
keyword argument 'fee'
  • 違反多型
    • 父/子類別的方法不同
Python 物件導向程式設計入門

一起來練習吧!

Python 物件導向程式設計入門

Preparing Video For Download...