Motivation#
In the last lesson we learnt how to create individual classes and one or more instances.
While this provides helpful abstraction and encapsulation of program logic it has some limitations.
Consider how we might have represented a Transaction account and a Term Deposit account (no withdrawal allowed), shown below.
Transaction Account
class TransactionAccount:
def __init__(self, bsb_number, account_number, balance, holder_name):
self.bsb_number = bsb_number
self.account_number = account_number
self.balance = balance
self.holder_name = holder_name
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
self.balance -= amount
Term Deposit Account
class TermDepositAccount:
def __init__(self, bsb_number, account_number, balance, holder_name):
self.bsb_number = bsb_number
self.account_number = account_number
self.balance = balance
self.holder_name = holder_name
def deposit(self, amount):
self.balance += amount
def get_earned_interest(self):
return 0.0235 * self.balance
Did you notice that most of the code is shared between the two classes?
We’ve spent a lot of time rewriting duplicate code. What’s even worse is that if we had to change the BSB/Account Number system we would have to change both classes!
In this lesson we will learn about inheritance which allows us to easily reuse code between classes, establish hierarchies of classes and compose object functionality from a set of other classes.