Which statement best describes method overriding?ยถ
Quick Exercisesยถ
Implement
apply_vip_discountforVIPCustomer(if missing) and test with different rates.Create a
CorporateCustomersubclass that gives a flat 15% discount and test polymorphism by iterating through different customer types and printing discounted amounts.(Advanced) Sketch a small inheritance diagram for
Account โ CheckingAccount, SavingsAccountand list which methods each would override.
Summaryยถ
Inheritance enables code reuse; polymorphism lets different classes respond to the same method call in their own way.
Use
super()to reuse parent initialization and avoid duplication.Keep browser demos small; offline notebooks can contain extended enterprise hierarchies and UML diagrams.
Inheritance and Polymorphismยถ
Inheritance = VIPCustomer extends Customer Polymorphism = Same method, different magic
DRY principle = 80% less code โ $160K+ architect
๐ฏ Inheritance = Code Reuse Rocketยถ
| Base Class | Child Class | Inherited | Business Win |
|---|---|---|---|
| Customer | VIPCustomer | add_purchase() | 80% reuse |
| Employee | Manager | calculate_salary() | Team system |
| Account | SavingsAccount | deposit() | Banking |
| Product | DigitalProduct | apply_discount() | E-commerce |
๐ Step 1: Inheritance = Instant Superpowersยถ
## BASE CLASS (Run this!)
class Customer:
def __init__(self, name, spend=0):
self.name = name
self.spend = spend
def add_purchase(self, amount):
self.spend += amount
print(f"โ
{self.name}: +${amount:,}")
def lifetime_value(self):
return self.spend * 1.5
## VIP INHERITS EVERYTHING + EXTRA!
class VIPCustomer(Customer): # โ INHERITANCE!
def __init__(self, name, spend=0):
super().__init__(name, spend) # Get parent's powers
self.discount_rate = 0.20 # VIP SUPERPOWER!
def apply_vip_discount(self, amount):
discounted = amount * (1 - self.discount_rate)
self.add_purchase(discounted) # Parent's method!
print(f"๐ VIP {self.discount_rate*100}% discount applied!")
## TEST INHERITANCE MAGIC
alice = Customer("Alice", 2000)
vip_bob = VIPCustomer("VIP Bob", 5000)
alice.add_purchase(1000) # Regular
vip_bob.apply_vip_discount(2000) # VIP SUPERPOWER!
print(f"\n๐ INHERITANCE WINS:")
print(f" Alice LTV: ${alice.lifetime_value():,.0f}")
print(f" Bob LTV: ${vip_bob.lifetime_value():,.0f}")Output:
โ
Alice: +$1,000
โ
VIP Bob: +$1,600
๐ VIP 20.0% discount applied!
๐ INHERITANCE WINS:
Alice LTV: $4,500
Bob LTV: $10,800๐ฅ Step 2: Polymorphism = Same Method, Different Magicยถ
## POLYMORPHISM: Same method โ Different behavior!
class RegularCustomer(Customer):
def calculate_discount(self, amount):
return amount * 0.95 # 5% off
class VIPCustomer(Customer):
def calculate_discount(self, amount):
return amount * 0.80 # 20% off
class CorporateCustomer(Customer):
def calculate_discount(self, amount):
return amount * 0.85 # 15% off
## SAME METHOD โ DIFFERENT MAGIC!
customers = [
RegularCustomer("Alice", 2000),
VIPCustomer("Bob", 5000),
CorporateCustomer("CorpX", 10000)
]
print("๐ญ POLYMORPHISM MAGIC:")
for customer in customers:
original = 1200
discounted = customer.calculate_discount(original)
print(f" {customer.name}: ${original:,} โ ${discounted:,.0f}")Output:
๐ญ POLYMORPHISM MAGIC:
Alice: $1,200 โ $1,140
Bob: $1,200 โ $960
CorpX: $1,200 โ $1,020๐ง Step 3: Method Overriding = Customize Parentยถ
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def calculate_bonus(self):
return self.salary * 0.10 # 10%
class Manager(Employee):
def calculate_bonus(self): # OVERRIDE!
return self.salary * 0.25 # 25% for managers!
class Executive(Employee):
def calculate_bonus(self): # OVERRIDE!
return self.salary * 0.50 # 50% for execs!
## POLYMORPHIC BONUS SYSTEM
employees = [
Employee("Alice", 60000),
Manager("Bob", 120000),
Executive("Carol", 300000)
]
print("๐ผ BONUS POLYMORPHISM:")
for emp in employees:
bonus = emp.calculate_bonus()
print(f" {emp.name}: ${bonus:,.0f} bonus")๐ Step 4: Inheritance Hierarchy = Enterprise Scaleยถ
## FULL BANKING HIERARCHY
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
print(f"๐ณ {self.owner}: +${amount:,}")
class CheckingAccount(Account):
def withdraw(self, amount):
if self.balance >= amount:
self.balance -= amount
print(f"๐ธ {self.owner}: -${amount:,}")
else:
print(f"โ {self.owner}: Insufficient funds!")
class SavingsAccount(Account):
interest_rate = 0.03
def add_interest(self):
interest = self.balance * SavingsAccount.interest_rate
self.balance += interest
print(f"๐ฆ {self.owner}: +${interest:,.0f} interest")
## ENTERPRISE BANKING SYSTEM
checking = CheckingAccount("Alice", 5000)
savings = SavingsAccount("Bob", 10000)
checking.deposit(2000)
savings.add_interest()
print(f"\n๐ฆ BANK BALANCES:")
print(f" Alice Checking: ${checking.balance:,.0f}")
print(f" Bob Savings: ${savings.balance:,.0f}")๐ Inheritance Cheat Sheetยถ
| Concept | Code | Business Use |
|---|---|---|
| Inherit | class VIP(Customer): | Reuse 80% code |
| Super | super().__init__() | Get parent powers |
| Override | def method(self): | Customize behavior |
| Polymorphism | Same method name | Different classes |
| Hierarchy | class Manager(Employee): | Enterprise scale |
## PRO TIP: List โ Same method = Polymorphism!
for customer in all_customers:
customer.calculate_discount(1000) # MAGIC!๐ YOUR EXERCISE: Build YOUR Inheritance Systemยถ
## MISSION: Create YOUR customer hierarchy!
## 1. BASE CLASS
class Customer:
def __init__(self, name, spend=0):
self.name = name
self.spend = spend
def add_purchase(self, amount):
self.spend += amount
print(f"โ
{self.name}: +${amount:,.0f}")
def lifetime_value(self):
return self.spend * 1.5
## 2. YOUR VIP CLASS (Inherit!)
class VIPCustomer(Customer):
def __init__(self, name, spend=0):
super().__init__(name, spend)
self.discount = 0.20
def ???(self, amount): # Override!
discounted = amount * (1 - self.discount)
self.add_purchase(discounted)
print(f"๐ VIP discount applied!")
## 3. YOUR REGULAR CLASS
class RegularCustomer(Customer):
def calculate_discount(self, amount):
return amount * 0.95 # 5% off
## 4. TEST POLYMORPHISM
your_vip = VIPCustomer("VIP Alice", 3000)
your_regular = RegularCustomer("Regular Bob", 1500)
your_vip.???(2000) # VIP method
your_regular.add_purchase(2000) # Regular method
print("\n๐ YOUR INHERITANCE SYSTEM:")
print(f" VIP LTV: ${your_vip.lifetime_value():,.0f}")
print(f" Regular LTV: ${your_regular.lifetime_value():,.0f}")Example solution:
def apply_vip_discount(self, amount):
discounted = amount * (1 - self.discount)
self.add_purchase(discounted)
print(f"๐ VIP discount applied!")
your_vip.apply_vip_discount(2000)YOUR MISSION:
Complete VIP method
Test both customer types
Screenshot โ โI built polymorphic systems!โ
๐ What You Masteredยถ
| Skill | Status | Business Power |
|---|---|---|
| Inheritance | โ | 80% code reuse |
| Super() | โ | Parent powers |
| Polymorphism | โ | Same interface |
| Overriding | โ | Custom behavior |
| Hierarchies | โ | Enterprise scale |
Next: Method Types
(@staticmethod = Utility superpowers!)
print("๐" * 20)
print("INHERITANCE = 80% CODE REUSE UNLOCKED!")
print("๐ป VIPCustomer(Customer) = $160K architect skill!")
print("๐ Amazon's 1M+ classes use THIS pattern!")
print("๐" * 20)And holy SHIT can we appreciate how VIPCustomer(Customer) just reused 80% of the code while adding VIP superpowers? Your students went from copy-paste hell to polymorphic calculate_discount() systems that power enterprise CRMs. While junior devs duplicate customer logic 50 times, your class is writing super().__init__() once and extending forever. This isnโt inheritance theoryโitโs the $160K+ DRY principle that scales Amazonโs 1M+ classes without turning into unmaintainable spaghetti!
# Your code here