Funktionalität durch Vererbung anpassen

Objektorientierte Programmierung in Python

Alex Yarosh

Content Quality Analyst @ DataCamp

eine Hierarchie von Kontoklassen

Objektorientierte Programmierung in Python

Was wir bisher haben

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

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

# Leere Klasse, die von BankAccount erbt
class SavingsAccount(BankAccount):
    pass
Objektorientierte Programmierung in Python

Konstruktoren anpassen

class SavingsAccount(BankAccount):    

    # Konstruktor speziell für SavingsAccount mit zusätzlichem Parameter
    def __init__(self, balance, interest_rate):  

# Elternkonstruktor mit ClassName.__init__() aufrufen BankAccount.__init__(self, balance) # <--- self ist ein SavingsAccount, aber auch ein BankAccount
# Mehr Funktionalität hinzufügen self.interest_rate = interest_rate
  • Elternkonstruktor zuerst ausführen mit Parent.__init__(self, args...)
  • Mehr Funktionalität hinzufügen
  • Elternkonstruktoren müssen nicht aufgerufen werden
Objektorientierte Programmierung in Python

Objekte mit angepasstem Konstruktor erstellen

# Objekt mit neuem Konstruktor erstellen
acct = SavingsAccount(1000, 0.03)
acct.interest_rate
0.03
Objektorientierte Programmierung in Python

Funktionalität hinzufügen

  • Methoden wie gewohnt hinzufügen
  • Daten aus Eltern- und Kindklasse nutzen
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)

Objektorientierte Programmierung in Python

eine Hierarchie von Kontoklassen

Objektorientierte Programmierung in Python

Funktionalität anpassen

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)
  • Signatur ändern (Parameter hinzufügen)
  • Parent.method(self, args...) verwenden, um eine Methode der Elternklasse aufzurufen
Objektorientierte Programmierung in Python
check_acct = CheckingAccount(1000, 25)

# Ruft withdraw von CheckingAccount auf
check_acct.withdraw(200)
# Ruft withdraw von CheckingAccount auf
check_acct.withdraw(200, fee=15)
bank_acct = BankAccount(1000)

# Ruft withdraw von 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'
Objektorientierte Programmierung in Python

Lass uns üben!

Objektorientierte Programmierung in Python

Preparing Video For Download...