6. Object-Oriented Programming (OOP)
OOP Part 2: Inheritance & Real-World Class Design
Extend existing classes without copying code using inheritance and super(), override methods cleanly, and combine objects together (like a ShoppingCart holding Products).
- Extend parent classes without duplicating code using inheritance and super()
- Customize inherited behavior by overriding parent methods
- Choose cleanly between inheritance ('is-a') and composition ('has-a')
In Lesson 18, you built your first BankAccount class. Now imagine your bank adds a Savings Account that works just like a normal BankAccount—deposit, withdraw, check balance—plus it also earns interest!
Should you copy and paste all 30 lines of BankAccount into a brand-new SavingsAccount class? No! That's why Python gives us Inheritance.
Inheriting Features (class Child(Parent):)
BankAccount (Parent)
owner, balance, deposit()
SavingsAccount(BankAccount)
+ rate, add_interest()
`SavingsAccount` automatically inherits `owner`, `balance`, and `.deposit()` from `BankAccount`.
Put the parent class inside parentheses right after the child class name:
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
class SavingsAccount(BankAccount):
def __init__(self, owner, balance=0, interest_rate=0.05):
super().__init__(owner, balance) # Reuse BankAccount's __init__!
self.interest_rate = interest_rate
def add_interest(self):
interest = round(self.balance * self.interest_rate, 2)
self.deposit(interest) # Inherited from BankAccount!
return interestLook at super().__init__(owner, balance):
super() simply means "call my parent class." So SavingsAccount gets owner, balance, and .deposit() for free, and only adds what is unique (interest_rate and .add_interest()).
You can also verify class relationships at runtime with Python's built-in checks:
isinstance(acct, SavingsAccount)→Trueisinstance(acct, BankAccount)→True(a child instance is also an instance of its parent!)issubclass(SavingsAccount, BankAccount)→True
Overriding & Extending a Parent Method
What if a child class needs to customize one method from its parent? Just define a method with the same name inside the child class—Python uses the child's version automatically! You can even call super().method() inside the override to extend the parent's behavior instead of rewriting it from scratch:
class FreeCourse:
def __init__(self, title):
self.title = title
def label(self):
return f"{self.title} (Free)"
class CertificateCourse(FreeCourse):
def label(self):
return f"{super().label()} + Certificate"Keep inheritance shallow (usually 1–2 levels deep). When a hierarchy grows to 4+ nested classes (Animal -> Mammal -> Pet -> Dog -> GuardDog), small parent edits break distant children unpredictably. Reach for composition whenever objects collaborate rather than share an identical identity.
Composition ("Has-A" Design)
Beginners sometimes overuse inheritance for everything. Remember this simple rule:
- Inheritance ("Is-A"): A
SavingsAccountis aBankAccount. - Composition ("Has-A"): A
ShoppingCarthasProductobjects inside a list!
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
class ShoppingCart:
def __init__(self):
self.items = []
def add(self, product):
self.items.append(product)
def total(self):
return round(sum(p.price for p in self.items), 2)Notice how natural cart.add(Product("Notebook", 6.50)) reads!
Try It Yourself in the Playground
Click “Run Code” to execute this snippet right in your browser.
Mini-Challenge: Create a StudentAccount(BankAccount) subclass that overrides deposit(self, amount) so every deposit gives a +$1 bonus (super().deposit(amount + 1)).
Quick Checkpoints
What does super().__init__(owner, balance) do inside a child class?
A Library class holds a list of Book objects (self.books = []). Which design relationship is this?