Interactions Between Classes#

Classes talking = Complete business systems Customer β†’ Order β†’ Product β†’ Payment = Enterprise

$190K+ architects design these relationships


🎯 Class Relationships = Enterprise Architecture#

Relationship

Code

Business Example

Scale

Composition

self.account = Account()

Customer HAS Account

1M+

Aggregation

self.orders = [Order()]

Customer HAS MANY Orders

10M+

Association

Order(customer)

Order KNOWS Customer

100M+

Dependency

Payment.process()

Payment USES Bank

Production


πŸš€ Step 1: Composition = β€œHAS-A” Relationship#

# CUSTOMER HAS ACCOUNT (Run this!)
class BankAccount:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance

    def deposit(self, amount):
        self.balance += amount
        print(f"πŸ’³ {self.owner}: +${amount:,} (Balance: ${self.balance:,.0f})")

class Customer:
    def __init__(self, name):
        self.name = name
        self.account = BankAccount(name)  # COMPOSITION!

    def make_payment(self, amount):
        self.account.deposit(amount)  # Account INSIDE Customer!

# FULL SYSTEM!
alice = Customer("Alice Johnson")
alice.make_payment(2500)

print(f"\nπŸ‘€ COMPLETE CUSTOMER:")
print(f"   {alice.name} account balance: ${alice.account.balance:,.0f}")

Output:

πŸ’³ Alice Johnson: +$2,500 (Balance: $2,500)
πŸ‘€ COMPLETE CUSTOMER:
   Alice Johnson account balance: $2,500

πŸ”₯ Step 2: Aggregation = β€œHAS MANY” Orders#

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:,} β†’ COMPLETED")

class Customer:
    def __init__(self, name):
        self.name = name
        self.orders = []  # AGGREGATION!

    def place_order(self, amount):
        order = Order(self, amount)
        self.orders.append(order)
        return order

    def total_orders_value(self):
        return sum(order.amount for order in self.orders)

# BUSINESS SYSTEM!
bob = Customer("Bob Smith")
order1 = bob.place_order(1200)
order2 = bob.place_order(800)

order1.process()
print(f"\nπŸ›’ Bob's order history: ${bob.total_orders_value():,.0f}")
print(f"   Orders count: {len(bob.orders)}")

🧠 Step 3: Association = Classes KNOW Each Other#

class Product:
    def __init__(self, name, price):
        self.name = name
        self.price = price

    def __str__(self):
        return f"{self.name} (${self.price:,.0f})"

class Order:
    def __init__(self, customer):
        self.customer = customer      # ASSOCIATION
        self.items = []

    def add_item(self, product, quantity=1):
        total = product.price * quantity
        self.items.append({"product": product, "qty": quantity, "total": total})
        print(f"πŸ›οΈ  Added {quantity}x {product} to {self.customer.name}'s order")

class Customer:
    def __init__(self, name):
        self.name = name

# REAL E-COMMERCE!
alice = Customer("Alice")
order = Order(alice)

laptop = Product("MacBook", 2500)
headphones = Product("AirPods", 200)

order.add_item(laptop)
order.add_item(headphones, 2)

print(f"\n🧾 Order Summary:")
for item in order.items:
    print(f"   {item['qty']}x {item['product']} = ${item['total']:,.0f}")

πŸ“Š Step 4: FULL ENTERPRISE SYSTEM#

# BANK + CUSTOMER + ACCOUNT + TRANSACTION = COMPLETE!
class Transaction:
    def __init__(self, account, amount, type_="deposit"):
        self.account = account
        self.amount = amount
        self.type = type_
        self.timestamp = "2024-01-15"

    def process(self):
        if self.type == "deposit":
            self.account.deposit(self.amount)
        else:
            print(f"πŸ’Έ {self.account.owner}: -${self.amount:,}")

class BankAccount:
    def __init__(self, owner):
        self.owner = owner
        self.balance = 0
        self.transactions = []

    def deposit(self, amount):
        self.balance += amount
        transaction = Transaction(self, amount, "deposit")
        self.transactions.append(transaction)
        print(f"πŸ’³ {self.owner}: +${amount:,} (Balance: ${self.balance:,.0f})")

class Customer:
    def __init__(self, name):
        self.name = name
        self.account = BankAccount(name)  # Composition

    def make_transaction(self, amount, type_="deposit"):
        transaction = Transaction(self.account, amount, type_)
        transaction.process()
        return transaction

# ENTERPRISE BANKING!
corp_customer = Customer("TechCorp")
corp_customer.make_transaction(10000, "deposit")
corp_customer.make_transaction(2500, "withdrawal")

print(f"\n🏦 Full System:")
print(f"   {corp_customer.name} balance: ${corp_customer.account.balance:,.0f}")
print(f"   Transactions: {len(corp_customer.account.transactions)}")

πŸ“‹ Relationship Cheat Sheet#

Relationship

Code Pattern

Business

When

Composition

self.account = Account()

Customer HAS Account

Strong ownership

Aggregation

self.orders = []

Customer HAS MANY Orders

Weak ownership

Association

Order(customer)

Order KNOWS Customer

Loose coupling

Dependency

Payment.use_bank()

Payment USES Bank

Temporary

# PRO DESIGN: Customer β†’ Orders β†’ Products
customer.orders[0].items[0].product.name

πŸ† YOUR EXERCISE: Build YOUR E-Commerce System#

# MISSION: Complete e-commerce relationships!

class Product:
    def __init__(self, name, price):
        self.name = name
        self.price = price

    def __str__(self):
        return f"{self.name} (${self.price:,.0f})"

class Order:
    def __init__(self, customer):
        self.customer = customer
        self.items = []

    def add_item(self, product, quantity=1):
        total = product.price * quantity
        self.items.append({"product": product, "qty": quantity, "total": total})
        print(f"πŸ›οΈ  {quantity}x {product} β†’ {self.customer.name}")

class Customer:
    def __init__(self, name):
        self.name = name
        self.orders = []  # AGGREGATION!

    def place_order(self):
        order = Order(self)
        self.orders.append(order)
        return order

# YOUR BUSINESS!
your_customer = Customer("???")  # YOUR name
your_order = your_customer.place_order()

# YOUR PRODUCTS!
your_product1 = Product("??? Pro", ???)    # YOUR product
your_product2 = Product("??? Max", ???)    # YOUR product

your_order.add_item(your_product1, 1)
your_order.add_item(your_product2, 2)

print("\nπŸš€ YOUR E-COMMERCE SYSTEM:")
print(f"   Customer: {your_customer.name}")
print(f"   Orders: {len(your_customer.orders)}")
print(f"   Items:")
for item in your_order.items:
    print(f"     {item['qty']}x {item['product']} = ${item['total']:,.0f}")

Example to test:

your_customer = Customer("Alice Johnson")
your_product1 = Product("MacBook Pro", 2500)
your_product2 = Product("AirPods", 200)

YOUR MISSION:

  1. Add YOUR customer/products

  2. Test full flow

  3. Screenshot β†’ β€œI built e-commerce systems!”


πŸŽ‰ What You Mastered#

Relationship

Status

Business Power

Composition

βœ…

HAS-A ownership

Aggregation

βœ…

HAS MANY orders

Association

βœ…

KNOWS customer

Full systems

βœ…

Enterprise scale

$190K design

βœ…

Architect level


Next: ML Exercise (Classes for ML pipelines = AI engineer!)

print("🎊" * 20)
print("CLASS INTERACTIONS = ENTERPRISE SYSTEMS!")
print("πŸ’» Customer β†’ Order β†’ Product = $190K architecture!")
print("πŸš€ Amazon's $500B checkout = THESE relationships!")
print("🎊" * 20)

And holy SHIT can we appreciate how customer.orders[0].items[0].product.name just created a complete e-commerce hierarchy that scales to Amazon’s 1B+ orders? Your students went from isolated classes to designing Customer β†’ Account β†’ Transaction systems that power real banks. While junior devs write 5000-line functions, your class is architecting composition + aggregation + association patterns that \(190K senior engineers use daily. This isn't relationship theoryβ€”it's the **enterprise blueprint** that builds \)TRILLION platforms without collapsing into chaos!

# Your code here