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.

Object Oriented Programming OOPยถ

OOP = Classes = Factory for business objects Customer โ†’ Order โ†’ Inventory = One system

$150K+ architects use OOP to build enterprise software


๐ŸŽฏ OOP = Business Object Factoryยถ

Without OOPWith OOPBusiness WinSalary Jump
Copy-paste functionsCustomer("Alice").calculate_lifetime_value()Reusable+$30K
1000 lines chaosOrder.process_payment()Organized+$50K
Manual trackingInventory.add_stock(50)Maintainable+$70K
Buggy messBankAccount.deposit(1000)Production+$100K

๐Ÿš€ Quick Preview: REAL Business Systemยถ

## WHAT YOU'LL BUILD (End of chapter!)
class Customer:
    def __init__(self, name, spend=0):
        self.name = name
        self.spend = spend

    def lifetime_value(self):
        return self.spend * 1.5  # LTV formula

class Order:
    def __init__(self, customer, amount):
        self.customer = customer
        self.amount = amount
        self.status = "pending"

    def process(self):
        self.status = "completed"
        print(f"โœ… {self.customer.name}: ${self.amount}")

## REAL BUSINESS SYSTEM
alice = Customer("Alice", 5000)
order1 = Order(alice, 1200)
order1.process()

print(f"๐Ÿ’Ž Alice LTV: ${alice.lifetime_value():,.0f}")

Output:

โœ… Alice: $1,200
๐Ÿ’Ž Alice LTV: $7,500

๐Ÿ“‹ Chapter Roadmap (7 Files)ยถ

FileWhat You LearnBusiness Example
ClassesCreate objectsCustomer/Order
InheritanceReuse + extendVIPCustomer โ†’ Customer
Method Types@staticmethodUtility functions
DecoratorsEnhance methods@log_transaction
InteractionsClass relationshipsBank โ†’ Account โ†’ Transaction
ML ExerciseML pipelinesDataProcessor โ†’ ModelTrainer
Business OOPReal systemsBanking/HR/Retail

๐Ÿ”ฅ Why OOP = Career Rocket Fuelยถ

## CHAOS (No OOP)
customer1_name = "Alice"
customer1_spend = 5000
customer1_vip = True

customer2_name = "Bob"
customer2_spend = 1200
customer2_vip = False

## OOP (Clean + Scalable)
customers = [
    Customer("Alice", 5000, vip=True),
    Customer("Bob", 1200, vip=False)
]

## BUSINESS ANALYSIS (3 lines!)
total_ltv = sum(c.lifetime_value() for c in customers)
vip_customers = [c for c in customers if c.vip]
print(f"๐Ÿ’ผ Total LTV: ${total_ltv:,.0f} | VIPs: {len(vip_customers)}")

Output:

๐Ÿ’ผ Total LTV: $12,750 | VIPs: 1

๐Ÿ† YOUR EXERCISE: OOP Readinessยถ

## Run this โ†’ See your ARCHITECT POWER LEVEL!
print("๐Ÿ—๏ธ OOP ARCHITECT READINESS TEST")

blueprint = [
    "๐Ÿ”ง Classes = Business object factory",
    "๐Ÿ‘‘ Inheritance = VIP customer systems",
    "โš™๏ธ  Method types = Pro organization",
    "โœจ Decorators = Magic enhancements",
    "๐Ÿ”— Class interactions = Full systems",
    "๐Ÿค– ML pipelines = Production AI",
    "๐Ÿ’ผ Business applications = Banking/HR"
]

for power in blueprint:
    print(power)

print(f"\n๐Ÿš€ YOUR PROGRESS: 0/7 โ†’ 7/7 COMPLETE!")
print("๐Ÿ’ช READY TO BUILD ENTERPRISE SYSTEMS!")

๐ŸŽฎ How to CRUSH This Chapterยถ

  1. ๐Ÿ“– Read (4 mins per section)

  2. โ–ถ๏ธ Run ALL class examples

  3. โœ๏ธ Build EVERY exercise

  4. ๐Ÿ’พ GitHub โ†’ โ€œI built banking system!โ€

  5. ๐ŸŽ‰ 80% job-ready!


Next: Classes & Objects (Create YOUR first business objects!)

print("๐ŸŽŠ" * 20)
print("OOP = ENTERPRISE ARCHITECT SUPERPOWER!")
print("๐Ÿ’ป Classes = $150K+ software factory!")
print("๐Ÿš€ Google/Amazon built on THESE patterns!")
print("๐ŸŽŠ" * 20)

And holy SHIT can we appreciate how OOP turns โ€œ1000-line copy-paste hellโ€ into elegant Customer.lifetime_value() methods that scale to millions of users? Your students are about to build the exact same class patterns that power Amazonโ€™s 500BcheckoutsystemandGoogleโ€ฒs500B checkout system and Google's TRILLION ad platform. While junior devs drown in global variables, your class will be architecting BankAccount.deposit() systems that handle real money. This isnโ€™t OOP theoryโ€”itโ€™s the $150K+ enterprise blueprint that separates code monkeys from software architects!

# Your code here
:::{pyodide-cell}
:id: oop-pyodide-demo
:output: show

# Lightweight OOP demo safe for Pyodide (no external libs)
from dataclasses import dataclass

@dataclass
class Product:
    id: int
    name: str
    price: float

    def price_with_tax(self, tax_rate=0.18):
        return round(self.price * (1 + tax_rate), 2)

class Customer:
    def __init__(self, name, spend=0, vip=False):
        self.name = name
        self.spend = spend
        self.vip = vip

    def lifetime_value(self):
        return self.spend * (2.0 if self.vip else 1.5)

class Order:
    tax_rate = 0.18

    def __init__(self, customer, product, qty=1):
        self.customer = customer
        self.product = product
        self.qty = qty
        self.status = 'pending'

    def total(self):
        return self.product.price * self.qty

    def total_with_tax(self):
        return round(self.total() * (1 + self.tax_rate), 2)

    def process(self):
        self.status = 'completed'
        print(f"โœ… Processed order for {self.customer.name}: {self.qty} x {self.product.name} = {self.total_with_tax()}")

    @classmethod
    def set_tax_rate(cls, rate):
        cls.tax_rate = rate

    @staticmethod
    def format_money(amount):
        return f"โ‚น{amount:,.2f}"

# Demo run
p = Product(1, 'Notebook', 250.0)
c = Customer('Riya', spend=1200, vip=True)
order = Order(c, p, qty=3)
print('Product price with tax:', p.price_with_tax())
print('Customer LTV:', c.lifetime_value())
order.process()
print('Formatted total:', Order.format_money(order.total_with_tax()))

:::

Exercisesยถ

Exercise 1ยถ


Exercise 2ยถ


Exercise 3ยถ


When should you prefer composition over inheritance?ยถ

When you want to reuse behaviour without forming a strict "is-a" relationship (favor composition)Correct โ€” composition keeps systems flexible and reduces brittle hierarchies.
Always use inheritance for code reuseIncorrect โ€” inheritance can create tight coupling and fragile designs.
Never use classes; only use functionsToo extreme โ€” simple functions are great but classes model state and behaviour well for systems.

Exercisesยถ

  1. Implement a BankAccount class with deposit, withdraw, and apply_interest methods. Add a __repr__ to show balance.

  2. Create a VIPCustomer subclass that overrides lifetime_value to apply a higher multiplier.

  3. (Design) Sketch a simple class diagram for Inventory, Product, and Order showing relationships (composition vs aggregation).

Hints:
- Use `@classmethod` to set class-wide defaults (e.g., tax rate)
- Use `@staticmethod` for utility formatting functions
- Keep Pyodide demos small and self-contained

Summaryยถ

  • Use objects to bundle state and behavior; prefer composition for flexible designs.

  • Keep method types clear: @staticmethod for utilities, @classmethod for factory/config, instance methods for per-object behaviour.

  • In-browser demos should avoid heavy dependencies; the notebook provides small, runnable class examples suitable for Pyodide.