# Classes and Objects
A concise, hands-on introduction to creating business objects in Python โ `Product`, `Customer`, and `Order`.{width=100}
Class = Blueprint | Object = Real customer/order
Customer("Alice") = Instant business object
This = Foundation of Amazon/Google enterprise systems
๐ฏ Classes = Business Object Factoryยถ
| Business Thing | Class | Object Example | Method |
|---|---|---|---|
| Customer | Customer | Customer("Alice") | .lifetime_value() |
| Order | Order | Order(alice, 1200) | .process_payment() |
| Product | Product | Product("Laptop", 1200) | .calculate_discount() |
| Inventory | Inventory | Inventory() | .add_stock(50) |
๐ Step 1: YOUR First Class (Run this!)ยถ
## CREATE YOUR FIRST BUSINESS CLASS
class Customer:
"""Customer object with business logic"""
def __init__(self, name, initial_spend=0):
self.name = name
self.spend = initial_spend
def add_purchase(self, amount):
self.spend += amount
print(f"โ
{self.name} purchased ${amount:,}")
def lifetime_value(self):
"""Business formula: spend * 1.5 multiplier"""
return self.spend * 1.5
def is_vip(self):
return self.spend > 3000
## CREATE REAL BUSINESS OBJECTS
alice = Customer("Alice Johnson", 1200)
bob = Customer("Bob Smith", 5000)
## USE BUSINESS METHODS
alice.add_purchase(2800)
bob.add_purchase(1500)
print("๐ฅ CUSTOMER SYSTEM:")
print(f" Alice LTV: ${alice.lifetime_value():,.0f} {'โญVIP' if alice.is_vip() else ''}")
print(f" Bob LTV: ${bob.lifetime_value():,.0f} {'โญVIP' if bob.is_vip() else ''}")Output:
โ
Alice Johnson purchased $2,800
โ
Bob Smith purchased $1,500
๐ฅ CUSTOMER SYSTEM:
Alice LTV: $6,000 โญVIP
Bob LTV: $9,750 โญVIP๐ฅ Step 2: Multiple Objects = Business Ecosystemยถ
## FULL BUSINESS SYSTEM
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def apply_discount(self, percentage):
self.price *= (1 - percentage/100)
print(f"๐ฐ {self.name} discounted to ${self.price:,.0f}")
class Order:
def __init__(self, customer, product, quantity=1):
self.customer = customer
self.product = product
self.quantity = quantity
self.total = product.price * quantity
def process_order(self):
self.customer.add_purchase(self.total)
print(f"๐ฆ Order processed: {self.customer.name} bought {self.quantity} {self.product.name}")
## BUILD ECOSYSTEM
laptop = Product("MacBook Pro", 2500)
headphones = Product("AirPods", 200)
order1 = Order(alice, laptop, 1)
order2 = Order(bob, headphones, 2)
## REAL BUSINESS FLOW
laptop.apply_discount(10)
order1.process_order()
order2.process_order()
print(f"\n๐ผ BUSINESS ECOSYSTEM:")
print(f" Alice total spend: ${alice.spend:,.0f}")
print(f" Bob total spend: ${bob.spend:,.0f}")๐ง Step 3: Class Attributes = Shared Business Dataยถ
class BankAccount:
# SHARED BY ALL ACCOUNTS
bank_name = "TechBank"
interest_rate = 0.03
def __init__(self, owner, initial_balance=0):
self.owner = owner
self.balance = initial_balance
def deposit(self, amount):
if amount > 0:
self.balance += amount
print(f"โ
{self.owner}: +${amount:,} (Balance: ${self.balance:,.0f})")
else:
print("โ Invalid deposit amount")
def get_interest(self):
return self.balance * BankAccount.interest_rate
## MULTIPLE ACCOUNTS SHARE BANK DATA
account1 = BankAccount("Alice", 10000)
account2 = BankAccount("Bob", 5000)
account1.deposit(2000)
account2.deposit(1500)
print(f"\n๐ฆ BANK SYSTEM:")
print(f" {BankAccount.bank_name} Interest:")
print(f" Alice: ${account1.get_interest():,.0f}")
print(f" Bob: ${account2.get_interest():,.0f}")๐ Class Anatomy Cheat Sheetยถ
| Part | Code | Business Use |
|---|---|---|
__init__ | def __init__(self, name): | Create object |
| Instance attr | self.name = name | Per-object data |
| Class attr | ClassName.rate = 0.03 | Shared data |
| Method | def lifetime_value(self): | Business logic |
| Self | self.spend | Current object |
## PRO TIP: Self = "This customer/order"
## self.name โ This customer's nameCaption: Class defines behavior; instances hold per-object state while sharing class-level defaults.
๐ YOUR EXERCISE: Build YOUR Business Systemยถ
## MISSION: Create YOUR e-commerce system!
## 1. YOUR PRODUCT CLASS
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def apply_discount(self, percentage):
self.price *= (1 - percentage / 100)
print(f"๐ฐ {self.name}: ${self.price:,.0f}")
## 2. YOUR CUSTOMER CLASS
class Customer:
def __init__(self, name, initial_spend=0):
self.name = name
self.spend = initial_spend
def add_purchase(self, amount):
self.spend += amount
print(f"โ
{self.name}: +${amount:,.0f}")
def lifetime_value(self):
return self.spend * 1.5
## 3. YOUR BUSINESS (Fill in YOUR data!)
your_customer = Customer("??? Smith", 1000) # YOUR customer
your_product = Product("??? Pro", 1500) # YOUR product
## 4. REAL BUSINESS FLOW
your_product.apply_discount(15) # 15% off
your_customer.add_purchase(your_product.price)
print("\n๐ YOUR E-COMMERCE SYSTEM:")
print(f" Customer: {your_customer.name}")
print(f" Product: {your_product.name} (${your_product.price:,.0f})")
print(f" LTV: ${your_customer.lifetime_value():,.0f}")Example to test:
your_customer = Customer("Alice Johnson", 1200)
your_product = Product("MacBook Pro", 2500)YOUR MISSION:
Create YOUR customer + product
Run business flow
Screenshot โ โI built e-commerce system!โ
๐ What You Masteredยถ
| Skill | Status | Business Power |
|---|---|---|
| Class creation | โ | Object factory |
__init__ | โ | Initialize objects |
| Methods | โ | Business logic |
| Self | โ | Object reference |
| Multiple objects | โ | Full systems |
Next: Inheritance (VIPCustomer โ Customer = Reuse + extend!)
print("๐" * 20)
print("CLASSES = BUSINESS OBJECT FACTORY UNLOCKED!")
print("๐ป Customer(\"Alice\").lifetime_value() = $150K skill!")
print("๐ Amazon checkout = THESE EXACT classes!")
print("๐" * 20)# Instructor hint: run the demo cell (below) then try the exercises.
# Use the demo to inspect `Product`, `Customer`, and `Order` behavior.
# Example quick test:
from dataclasses import dataclass
@dataclass
class ProductSample:
id: int
name: str
price: float
class CustomerSample:
def __init__(self, name):
self.name = name
self.spend = 0
def add_purchase(self, amount):
self.spend += amount
p = ProductSample(1, 'Sample', 100.0)
c = CustomerSample('Tester')
c.add_purchase(p.price)
print('Sample LTV (est):', c.spend * 1.5)Which is true about class vs instance attributes?ยถ
Class attributes are shared across instances; instance attributes are per-objectCorrect โ changing a class attribute affects all instances unless overridden.
Instance attributes are shared across instancesIncorrect โ instance attributes are unique per object.
Class attributes cannot be modified at runtimeIncorrect โ class attributes can be updated, affecting new and existing instances (unless shadowed).
Summary & Next Stepsยถ
You built
Product,Customer, and saw class vs instance attributes in action.Next notebook:
Programming_for_Business/notebooks/encapsulation.ipynbโ weโll add private attributes, property decorators, and defensive methods there.