Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Which statement best describes method overriding?ยถ

A child class defines a method with the same name as the parent to change behaviorCorrect โ€” overriding customizes parent behaviour.
A child class copies parent methods without modificationIncorrect โ€” overriding intentionally replaces behaviour.
Overriding prevents access to parent methodsIncorrect โ€” you can still call parent methods via `super()`.

Quick Exercisesยถ

  1. Implement apply_vip_discount for VIPCustomer (if missing) and test with different rates.

  2. Create a CorporateCustomer subclass that gives a flat 15% discount and test polymorphism by iterating through different customer types and printing discounted amounts.

  3. (Advanced) Sketch a small inheritance diagram for Account โ†’ CheckingAccount, SavingsAccount and 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 ClassChild ClassInheritedBusiness Win
CustomerVIPCustomeradd_purchase()80% reuse
EmployeeManagercalculate_salary()Team system
AccountSavingsAccountdeposit()Banking
ProductDigitalProductapply_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ยถ

ConceptCodeBusiness Use
Inheritclass VIP(Customer):Reuse 80% code
Supersuper().__init__()Get parent powers
Overridedef method(self):Customize behavior
PolymorphismSame method nameDifferent classes
Hierarchyclass 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:

  1. Complete VIP method

  2. Test both customer types

  3. Screenshot โ†’ โ€œI built polymorphic systems!โ€


๐ŸŽ‰ What You Masteredยถ

SkillStatusBusiness 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

Exercisesยถ

Exercise 1ยถ


Exercise 2ยถ


Exercise 3ยถ