Designing for inheritance and polymorphism

Object-Oriented Programming in Python

Alex Yarosh

Content Quality Analyst @ DataCamp

Polymorphism

 

 

Using a unified interface to operate on objects of different classes

Object-Oriented Programming in Python

account classes hierarchy

Object-Oriented Programming in Python

All that matters is the interface

# Withdraw amount from each of accounts in list_of_accounts
def batch_withdraw(list_of_accounts, amount):
   for acct in list_of_accounts:
      acct.withdraw(amount)

b, c, s = BankAccount(1000), CheckingAccount(2000), SavingsAccount(3000) batch_withdraw([b,c,s]) # <-- Will use BankAccount.withdraw(), # then CheckingAccount.withdraw(), # then SavingsAccount.withdraw()
  • batch_withdraw() doesn't need to check the object to know which withdraw() to call
Object-Oriented Programming in Python

Liskov substitution principle

 

Base class should be interchangeable with any of its subclasses without altering any properties of the program

Wherever BankAccount works, CheckingAccount should work as well

photo of Barbara Liskov

Object-Oriented Programming in Python

Liskov substitution principle

 

Base class should be interchangeable with any of its subclasses without altering any properties of the program

Syntactically
  • function signatures are compatible
    • arguments, returned values
Semantically
  • the state of the object and the program remains consistent
    • subclass method doesn't strengthen input conditions
    • subclass method doesn't weaken output conditions
    • no additional exceptions
Object-Oriented Programming in Python

Violating LSP

Syntactic incompatibility

BankAccount.withdraw() requires 1 parameter, but CheckingAccount.withdraw() requires 2

Subclass strengthening input conditions

BankAccount.withdraw() accepts any amount, but CheckingAccount.withdraw() assumes that the amount is limited

Subclass weakening output conditions

BankAccount.withdraw() can only leave a positive balance or cause an error, CheckingAccount.withdraw() can leave balance negative

Object-Oriented Programming in Python

Violating LSP

→ Changing additional attributes in subclass's method

→ Throwing additional exceptions in subclass's method

Object-Oriented Programming in Python

 

 

 

 

$$\text{\textbf{\Huge{No LSP -- No Inheritance}}}$$

Object-Oriented Programming in Python

Let's practice!

Object-Oriented Programming in Python

Preparing Video For Download...