継承で機能をカスタマイズする

Python によるオブジェクト指向プログラミング

Alex Yarosh

Content Quality Analyst @ DataCamp

口座クラスの階層

Python によるオブジェクト指向プログラミング

ここまでの内容

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

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

# BankAccount を継承した空のクラス
class SavingsAccount(BankAccount):
    pass
Python によるオブジェクト指向プログラミング

コンストラクタのカスタマイズ

class SavingsAccount(BankAccount):    

    # SavingsAccount 専用のコンストラクタ(追加引数あり)
    def __init__(self, balance, interest_rate):  

# ClassName.__init__() で親のコンストラクタを呼ぶ BankAccount.__init__(self, balance) # <--- self は SavingsAccount かつ BankAccount
# 機能を追加 self.interest_rate = interest_rate
  • Parent.__init__(self, args...) で親のコンストラクタを先に実行可
  • 機能を追加
  • 親のコンストラクタを必ずしも呼ぶ必要はない
Python によるオブジェクト指向プログラミング

カスタムコンストラクタで作成

# 新しいコンストラクタでオブジェクトを作成
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

  # 新機能
  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)

# CheckingAccount の withdraw が呼ばれる
check_acct.withdraw(200)
# CheckingAccount の withdraw が呼ばれる
check_acct.withdraw(200, fee=15)
bank_acct = BankAccount(1000)

# BankAccount の withdraw が呼ばれる
bank_acct.withdraw(200)
# エラーが発生
bank_acct.withdraw(200, fee=15)
TypeError: withdraw() got an unexpected
 keyword argument 'fee'
Python によるオブジェクト指向プログラミング

Let's practice!

Python によるオブジェクト指向プログラミング

Preparing Video For Download...