Object-Oriented Programming in Python
Alex Yarosh
Content Quality Analyst @ DataCamp
# 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
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
Base class should be interchangeable with any of its subclasses without altering any properties of the program
→ 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
→ Changing additional attributes in subclass's method
→ Throwing additional exceptions in subclass's method
$$\text{\textbf{\Huge{No LSP -- No Inheritance}}}$$
Object-Oriented Programming in Python