透過繼承自訂功能

Python 物件導向程式設計

Alex Yarosh

Content Quality Analyst @ 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 specifically for SavingsAccount with an additional parameter
    def __init__(self, balance, interest_rate):  

# Call the parent constructor using ClassName.__init__() BankAccount.__init__(self, balance) # <--- self is a SavingsAccount but also a BankAccount
# 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) self.limit = limit
def deposit(self, amount): self.balance += amount
def withdraw(self, amount, fee=0):
if fee <= self.limit: BankAccount.withdraw(self, amount + fee) else: BankAccount.withdraw(self, amount + self.limit)
  • 可更改簽章(加入參數)
  • Parent.method(self, args...) 呼叫父類別的方法
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...