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

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

George Boorman

Curriculum Manager, 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__() で呼ぶ # self は SavingsAccount かつ BankAccount BankAccount.__init__(self, balance)
# 機能を追加 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によるオブジェクト指向プログラミング入門

第2の子クラスを追加

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): # 新しい fee 引数
if amount <= self.limit: BankAccount.withdraw(self, amount + fee) else: pass # 条件を満たさない場合は実行しない
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によるオブジェクト指向プログラミング入門

Passons à la pratique !

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

Preparing Video For Download...