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