Accounts with Rules
Advanced · Stretch · from Python Inheritance: Subclasses, Polymorphism, and super()
From the lesson: Python Inheritance: Subclasses, Polymorphism, and super()
Think about how scientists classify animals. A Dog is a type of Mammal, which is a type of Animal. Each level inherits traits from the one above it: all animals breathe, all mammals are warm-blooded, and all dogs bark.
Read the lessonWrite three classes for a bank:
Account(owner, balance=0) has deposit(amount), which adds money, and withdraw(amount), which takes the money and returns True when there is enough, or changes nothing and returns False when there is not.SavingsAccount(owner, balance=0) is an Account that allows at most 3 withdrawals until new_month() is called. A 4th withdrawal returns False. A withdrawal that was refused does not count as one of the 3.CheckingAccount(owner, balance=0, overdraft=0) is an Account whose balance may go below zero, down to -overdraft but not further.c = CheckingAccount("cy", 50, overdraft=100)
c.withdraw(150) # True
c.balance # -100
c.withdraw(1) # FalseKeep the money rules in Account and reuse them in the subclasses with super(). Some of the tests are hidden.
class Account:
pass
class SavingsAccount(Account):
pass
class CheckingAccount(Account):
pass
Solution unlocks after your first Check
What Check runs
Your code runs first, then each of these lines, and 5 more that stay hidden. The output must match exactly.
| Runs | Expected output |
|---|---|
| a = Account("ann", 100); a.withdraw(30), a.withdraw(80), a.balance | (True, False, 70) |
| s = SavingsAccount("bob", 100); s.withdraw(10), s.withdraw(10), s.withdraw(10), s.withdraw(10), s.balance | (True, True, True, False, 70) |
More Inheritance exercises
- Create a Vehicle SubclassBeginner
- Override the describe() MethodBeginner
- Predict the super() OutputIntermediate
- Fix the Inheritance BugIntermediate
- Build a Shape Area CalculatorIntermediate
- Build a Notification SystemAdvanced
All Python exercises · 50 practice problems · Object-Oriented Programming quiz