Introductie tot objectgeoriënteerd programmeren in Python
George Boorman
Curriculum Manager, DataCamp

class BankAccount:
def __init__(self, balance):
self.balance = balance
def withdraw(self, amount):
self.balance -=amount
# Lege klasse geërfd van BankAccount
class SavingsAccount(BankAccount):
pass
class SavingsAccount(BankAccount): # Constructor voor SavingsAccount met een extra argument def __init__(self, balance, interest_rate):# Roep de ouderconstructor aan met ClassName.__init__() # self is een SavingsAccount maar ook een BankAccount BankAccount.__init__(self, balance)# Voeg extra functionaliteit toe self.interest_rate = interest_rate
Parent.__init__(self, args...)# Maak het object met de nieuwe constructor
acct = SavingsAccount(1000, 0.03)
acct.interest_rate
0.03
class SavingsAccount(BankAccount):
def __init__(self, balance, interest_rate):
BankAccount.__init__(self, balance)
self.interest_rate = interest_rate
# Nieuwe functionaliteit
def compute_interest(self, n_periods=1):
return self.balance * ( (1 + self.interest_rate) ** n_periods - 1)

class CheckingAccount(BankAccount):def __init__(self, balance, limit): BankAccount.__init__(self, balance) # Roep de constructor van de ouderklasse aan self.limit = limitdef deposit(self, amount): self.balance += amountdef withdraw(self, amount, fee=0): # Nieuwe fee-parameterif amount <= self.limit: BankAccount.withdraw(self, amount + fee) else: pass # Wordt niet uitgevoerd als de voorwaarde niet klopt
check_acct = CheckingAccount(1000, 25) # Roept withdraw aan van CheckingAccount check_acct.withdraw(200)# Roept withdraw aan van CheckingAccount check_acct.withdraw(200, fee=15)
bank_acct = BankAccount(1000) # Roept withdraw aan van BankAccount bank_acct.withdraw(200)# Levert een fout op bank_acct.withdraw(200, fee=15)
TypeError: withdraw() got an unexpected
keyword argument 'fee'
Introductie tot objectgeoriënteerd programmeren in Python