Einführung in objektorientierte Programmierung in Python
George Boorman
Curriculum Manager, DataCamp

class BankAccount:
def __init__(self, balance):
self.balance = balance
def withdraw(self, amount):
self.balance -=amount
# Leere Klasse, geerbt von BankAccount
class SavingsAccount(BankAccount):
pass
class SavingsAccount(BankAccount): # Konstruktor für SavingsAccount mit zusätzlichem Argument def __init__(self, balance, interest_rate):# Elternkonstruktor mit ClassName.__init__() aufrufen # self ist ein SavingsAccount, aber auch ein BankAccount BankAccount.__init__(self, balance)# Mehr Funktionalität hinzufügen self.interest_rate = interest_rate
Parent.__init__(self, args...) aufrufen# Objekt mit dem neuen Konstruktor erzeugen
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
# Neue Funktionalität
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) # Eltern-Konstruktor aufrufen self.limit = limitdef deposit(self, amount): self.balance += amountdef withdraw(self, amount, fee=0): # Neues Argument feeif amount <= self.limit: BankAccount.withdraw(self, amount + fee) else: pass # Läuft nicht, wenn die Bedingung nicht erfüllt ist
check_acct = CheckingAccount(1000, 25) # Ruft withdraw aus CheckingAccount auf check_acct.withdraw(200)# Ruft withdraw aus CheckingAccount auf check_acct.withdraw(200, fee=15)
bank_acct = BankAccount(1000) # Ruft withdraw aus BankAccount auf bank_acct.withdraw(200)# Führt zu einem Fehler bank_acct.withdraw(200, fee=15)
TypeError: withdraw() got an unexpected
keyword argument 'fee'
Einführung in objektorientierte Programmierung in Python