Project: E-Commerce Mini Project
Build an online shopping system with products, carts, orders, and customers -- combining all four OOP pillars.
Project Overview
This is the final project of the course. You will build a simplified e-commerce system that models how real online stores work. Products have stock, customers have carts, and orders track purchase history. Every OOP concept you have learned comes together here.
All Four Pillars Combined
Encapsulation
Product stock and prices are protected. Cart items cannot be modified directly -- only through add/remove methods.
Inheritance
Could be extended with DigitalProduct or PhysicalProduct subclasses (see extension exercises).
Polymorphism
Custom __str__ and __eq__ methods let products behave naturally with print() and ==.
Abstraction
The Customer class provides a simple checkout() interface that hides the complexity of creating orders and reducing stock.
Step 1: The Product Class
Every product has a name, price, and stock count. We use properties to control access and operator overloading to customize how products are printed and compared.
class Product:
def __init__(self, name, price, stock=0):
self._name = name
self._price = price
self._stock = stock
@property
def name(self):
return self._name
@property
def price(self):
return self._price
@property
def in_stock(self):
return self._stock > 0
@property
def stock(self):
return self._stock
def reduce_stock(self, quantity=1):
if quantity <= self._stock:
self._stock -= quantity
return True
return False
def __str__(self):
status = "In Stock" if self.in_stock else "Out of Stock"
return f"{self._name} - ${self._price:.2f} ({status})"
def __eq__(self, other):
return isinstance(other, Product) and self._name == other._name
Operator overloading: The __eq__ method lets us compare products with ==. Two products are considered equal if they have the same name. The __str__ method gives us a nice output when we print() a product.
Step 2: The Cart Class
The cart holds products the customer wants to buy. It tracks quantities and calculates totals. Items are stored in a dictionary for fast lookup by product name.
class Cart:
def __init__(self):
self._items = {} # {product_name: {"product": Product, "quantity": int}}
def add(self, product, quantity=1):
if product.in_stock:
if product.name in self._items:
self._items[product.name]["quantity"] += quantity
else:
self._items[product.name] = {
"product": product,
"quantity": quantity
}
def remove(self, product_name):
self._items.pop(product_name, None)
def update_quantity(self, product_name, quantity):
if product_name in self._items:
if quantity <= 0:
self.remove(product_name)
else:
self._items[product_name]["quantity"] = quantity
@property
def total(self):
return sum(
item["product"].price * item["quantity"]
for item in self._items.values()
)
@property
def item_count(self):
return sum(item["quantity"] for item in self._items.values())
@property
def is_empty(self):
return len(self._items) == 0
def clear(self):
self._items = {}
def get_items(self):
return dict(self._items)
def __str__(self):
if not self._items:
return "Cart is empty"
lines = ["Shopping Cart:"]
for name, item in self._items.items():
subtotal = item["product"].price * item["quantity"]
lines.append(f" {name} x{item['quantity']} = ${subtotal:.2f}")
lines.append(f" Total: ${self.total:.2f}")
return "\n".join(lines)
Encapsulation at work: The _items dictionary is private. Users interact through add(), remove(), and update_quantity(). The total is always calculated fresh from the current items, so it can never be out of sync.
Step 3: The Order Class
When a customer checks out, the cart contents become an order. Each order has a unique ID, a snapshot of the items purchased, and a status that tracks its progress.
class Order:
_next_id = 1
def __init__(self, items, total):
self._order_id = f"ORD{Order._next_id:04d}"
Order._next_id += 1
self._items = items # Snapshot of cart items
self._total = total
self._status = "Pending"
@property
def order_id(self):
return self._order_id
@property
def total(self):
return self._total
@property
def status(self):
return self._status
def update_status(self, new_status):
valid = ["Pending", "Confirmed", "Shipped", "Delivered", "Cancelled"]
if new_status in valid:
self._status = new_status
def __str__(self):
lines = [f"Order {self._order_id} [{self._status}]"]
for name, item in self._items.items():
subtotal = item["product"].price * item["quantity"]
lines.append(f" {name} x{item['quantity']} = ${subtotal:.2f}")
lines.append(f" Order Total: ${self._total:.2f}")
return "\n".join(lines)
Why a snapshot? The order stores a copy of the cart items at the time of purchase. This way, even if product prices change later, the order still reflects what the customer actually paid.
Step 4: The Customer Class
The Customer class brings everything together. Each customer has their own cart and order history. The checkout() method handles the complex process of converting a cart into an order.
class Customer:
def __init__(self, name, email):
self._name = name
self._email = email
self.cart = Cart()
self._orders = []
@property
def name(self):
return self._name
@property
def email(self):
return self._email
def add_to_cart(self, product, quantity=1):
self.cart.add(product, quantity)
def remove_from_cart(self, product_name):
self.cart.remove(product_name)
def checkout(self):
if self.cart.is_empty:
print("Cart is empty. Nothing to checkout.")
return None
# Check stock for all items
for name, item in self.cart.get_items().items():
if not item["product"].reduce_stock(item["quantity"]):
print(f"Not enough stock for {name}.")
return None
# Create order from cart
order = Order(self.cart.get_items(), self.cart.total)
self._orders.append(order)
self.cart.clear()
order.update_status("Confirmed")
return order
def view_orders(self):
if not self._orders:
print(f"{self._name} has no orders yet.")
return
print(f"\n--- Orders for {self._name} ---")
for order in self._orders:
print(order)
print()
def __str__(self):
return f"{self._name} ({self._email}) - {len(self._orders)} orders"
Abstraction: The checkout() method hides a lot of complexity. It checks stock, reduces inventory, creates an order, clears the cart, and updates the status. The caller just says customer.checkout() without worrying about the steps.
Step 5: Using the System
Here is a complete demo that creates products, a customer, adds items to the cart, checks out, and views order history.
# Create products
laptop = Product("Laptop", 999.99, stock=5)
headphones = Product("Headphones", 49.99, stock=10)
mouse = Product("Mouse", 29.99, stock=15)
# Display products
print("--- Product Catalog ---")
print(laptop)
print(headphones)
print(mouse)
# Create a customer
alice = Customer("Alice", "alice@email.com")
# Add items to cart
alice.add_to_cart(laptop)
alice.add_to_cart(headphones, 2)
alice.add_to_cart(mouse)
# View cart
print(f"\n{alice.cart}")
# Checkout
order = alice.checkout()
print(f"\nOrder placed! {order.order_id}")
# View updated stock
print(f"\nLaptop stock: {laptop.stock}")
print(f"Headphones stock: {headphones.stock}")
# Make another purchase
alice.add_to_cart(mouse, 3)
order2 = alice.checkout()
# View all orders
alice.view_orders()
Expected Output:
--- Product Catalog ---
Laptop - $999.99 (In Stock)
Headphones - $49.99 (In Stock)
Mouse - $29.99 (In Stock)
Shopping Cart:
Laptop x1 = $999.99
Headphones x2 = $99.98
Mouse x1 = $29.99
Total: $1129.96
Order placed! ORD0001
Laptop stock: 4
Headphones stock: 8
--- Orders for Alice ---
Order ORD0001 [Confirmed]
Laptop x1 = $999.99
Headphones x2 = $99.98
Mouse x1 = $29.99
Order Total: $1129.96
Order ORD0002 [Confirmed]
Mouse x3 = $89.97
Order Total: $89.97
Full Course Recap: All 7 Weeks
Week 1: Python Basics
Variables, data types, conditionals, loops, and functions. The foundation that everything else builds on.
Week 2: Introduction to OOP
Classes, objects, attributes, and methods. Learning to think about code as real-world things with properties and behaviors.
Week 3: Constructors & Encapsulation
The __init__ method, instance vs class variables, access modifiers, getters/setters, and data hiding. Protecting your data.
Week 4: Inheritance
Parent and child classes, method overriding, super(), and different types of inheritance. Building on existing code.
Week 5: Polymorphism
Method overriding in depth, operator overloading, and duck typing. Same interface, different behaviors.
Week 6: Abstraction & Advanced
Abstract classes, interfaces, multiple inheritance, and the diamond problem. Advanced tools for complex designs.
Week 7: Real Projects
Bank system, student management, and e-commerce. Putting all four pillars together in complete, working applications.
Congratulations!
You have completed the entire OOP in Python course. Over 7 weeks, you went from Python basics to building complete, real-world applications using all four pillars of Object-Oriented Programming.
What to Learn Next
Databases
Learn to save your objects to a database using SQLite or an ORM like SQLAlchemy. Your bank accounts and student records could persist between program runs.
Web Development
Frameworks like Flask and Django use OOP heavily. Your e-commerce project could become a real web application.
Design Patterns
Learn established patterns like Factory, Observer, Strategy, and Decorator. These are reusable solutions to common OOP problems.
Extension Exercises
Exercise 1: Discount Codes
Create a DiscountCode class with a code string and a percentage off. Add an apply_discount(code) method to the Cart that reduces the total. Make sure each code can only be used once.
Exercise 2: Product Categories with Inheritance
Create subclasses of Product: DigitalProduct (no stock limit, instant delivery) and PhysicalProduct (has weight, shipping cost). Override methods as needed.
Exercise 3: Payment Processing with Polymorphism
Create an abstract PaymentMethod class with a process_payment(amount) method. Implement CreditCard, DebitCard, and DigitalWallet subclasses, each with different processing logic.
Final Summary
- You built a complete e-commerce system with products, carts, orders, and customers.
- Encapsulation protects product stock and cart items from invalid access.
- Polymorphism through
__str__and__eq__makes objects behave naturally. - Abstraction hides checkout complexity behind a single method call.
- You have now completed all 39 lessons across 7 weeks of OOP in Python.
- Keep building projects -- that is the best way to solidify your skills!