0% found this document useful (0 votes)
4 views6 pages

Project Py PDF

The document is a Python script implementing an online shopping cart system with classes for products, cart items, and the shopping cart itself. It includes functionality for managing physical and digital products, displaying product details, adding/removing items from the cart, and saving/loading cart and product data from JSON files. The script also features a console interface for user interaction.

Uploaded by

thegeekshivansh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views6 pages

Project Py PDF

The document is a Python script implementing an online shopping cart system with classes for products, cart items, and the shopping cart itself. It includes functionality for managing physical and digital products, displaying product details, adding/removing items from the cart, and saving/loading cart and product data from JSON files. The script also features a console interface for user interaction.

Uploaded by

thegeekshivansh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

project.

py

1 import json
2 from typing import Dict
3
4
5 # -------------------- Product Base Class --------------------
6 class Product:
7 def __init__(self, product_id: str, name: str, price: float, quantity_available: int):
8 self._product_id = product_id
9 self._name = name
10 self._price = price
11 self._quantity_available = quantity_available
12
13 @property
14 def product_id(self):
15 return self._product_id
16
17 @property
18 def name(self):
19 return self._name
20
21 @property
22 def price(self):
23 return self._price
24
25 @property
26 def quantity_available(self):
27 return self._quantity_available
28
29 @quantity_available.setter
30 def quantity_available(self, value):
31 if value >= 0:
32 self._quantity_available = value
33
34 def decrease_quantity(self, amount: int) -> bool:
35 if 0 <= amount <= self._quantity_available:
36 self._quantity_available -= amount
37 return True
38 return False
39
40 def increase_quantity(self, amount: int):
41 self._quantity_available += amount
42
43 def display_details(self) -> str:
44 return f"[{self.product_id}] {self.name} - ₹{self.price:.2f}
({self.quantity_available} in stock)"
45
46 def to_dict(self) -> dict:
47 return {
48 "type": "generic",
49 "product_id": self._product_id,
50 "name": self._name,
51 "price": self._price,
52 "quantity_available": self._quantity_available
53 }
54
55
56 # -------------------- PhysicalProduct --------------------
57 class PhysicalProduct(Product):
58 def __init__(self, product_id, name, price, quantity_available, weight):
59 super().__init__(product_id, name, price, quantity_available)
60 self._weight = weight
61
62 @property
63 def weight(self):
64 return self._weight
65
66 def display_details(self):
67 return f"[{self.product_id}] {self.name} - ₹{self.price:.2f}, {self.weight}kg
({self.quantity_available} in stock)"
68
69 def to_dict(self):
70 data = super().to_dict()
71 data.update({"weight": self._weight, "type": "physical"})
72 return data
73
74
75 # -------------------- DigitalProduct --------------------
76 class DigitalProduct(Product):
77 def __init__(self, product_id, name, price, quantity_available, download_link):
78 super().__init__(product_id, name, price, quantity_available)
79 self._download_link = download_link
80
81 @property
82 def download_link(self):
83 return self._download_link
84
85 def display_details(self):
86 return f"[{self.product_id}] {self.name} - ₹{self.price:.2f} (Digital) | Link:
{self._download_link}"
87
88 def to_dict(self):
89 data = super().to_dict()
90 data.update({"download_link": self._download_link, "type": "digital"})
91 return data
92
93
94 # -------------------- CartItem --------------------
95 class CartItem:
96 def __init__(self, product: Product, quantity: int):
97 self._product = product
98 self._quantity = quantity
99
100 @property
101 def product(self):
102 return self._product
103
104 @property
105 def quantity(self):
106 return self._quantity
107
108 @quantity.setter
109 def quantity(self, value):
110 if value >= 0:
111 self._quantity = value
112
113 def calculate_subtotal(self) -> float:
114 return self._quantity * self._product.price
115
116 def __str__(self):
117 return f"{self.product.name} | Qty: {self.quantity} | Price: ₹
{self.product.price:.2f} | Subtotal: ₹{self.calculate_subtotal():.2f}"
118
119 def to_dict(self):
120 return {"product_id": self.product.product_id, "quantity": self.quantity}
121
122
123 # -------------------- ShoppingCart --------------------
124 class ShoppingCart:
125 def __init__(self, product_catalog_file='products.json', cart_state_file='cart.json'):
126 self._items: Dict[str, CartItem] = {}
127 self._product_catalog_file = product_catalog_file
128 self._cart_state_file = cart_state_file
129 self.catalog = self._load_catalog()
130 self._load_cart_state()
131
132 def _load_catalog(self):
133 try:
134 with open(self._product_catalog_file, 'r') as f:
135 data = json.load(f)
136 catalog = {}
137 for item in data:
138 type_ = item.get("type", "generic")
139 if type_ == "physical":
140 product = PhysicalProduct(**item)
141 elif type_ == "digital":
142 product = DigitalProduct(**item)
143 else:
144 product = Product(**item)
145 catalog[product.product_id] = product
146 return catalog
147 except FileNotFoundError:
148 return {}
149
150 def _load_cart_state(self):
151 try:
152 with open(self._cart_state_file, 'r') as f:
153 data = json.load(f)
154 for item in data:
155 pid = item['product_id']
156 quantity = item['quantity']
157 if pid in self.catalog:
158 self._items[pid] = CartItem(self.catalog[pid], quantity)
159 except FileNotFoundError:
160 pass
161
162 def _save_catalog(self):
163 with open(self._product_catalog_file, 'w') as f:
164 json.dump([p.to_dict() for p in self.catalog.values()], f, indent=2)
165
166 def _save_cart_state(self):
167 with open(self._cart_state_file, 'w') as f:
168 json.dump([item.to_dict() for item in self._items.values()], f, indent=2)
169
170 def add_item(self, product_id: str, quantity: int) -> bool:
171 if product_id in self.catalog and self.catalog[product_id].quantity_available >=
quantity:
172 if product_id in self._items:
173 self._items[product_id].quantity += quantity
174 else:
175 self._items[product_id] = CartItem(self.catalog[product_id], quantity)
176 self.catalog[product_id].decrease_quantity(quantity)
177 self._save_cart_state()
178 return True
179 return False
180
181 def remove_item(self, product_id: str) -> bool:
182 if product_id in self._items:
183 self.catalog[product_id].increase_quantity(self._items[product_id].quantity)
184 del self._items[product_id]
185 self._save_cart_state()
186 return True
187 return False
188
189 def update_quantity(self, product_id: str, new_quantity: int) -> bool:
190 if product_id not in self._items or new_quantity < 0:
191 return False
192 current_item = self._items[product_id]
193 diff = new_quantity - current_item.quantity
194 if diff > 0 and self.catalog[product_id].quantity_available < diff:
195 return False
196 self.catalog[product_id].decrease_quantity(diff) if diff > 0 else
self.catalog[product_id].increase_quantity(-diff)
197 current_item.quantity = new_quantity
198 self._save_cart_state()
199 return True
200
201 def get_total(self) -> float:
202 return sum(item.calculate_subtotal() for item in self._items.values())
203
204 def display_cart(self):
205 if not self._items:
206 print(" Your cart is empty.")
207 for item in self._items.values():
208 print(item)
209 print(f"Total: ₹{self.get_total():.2f}")
210
211 def display_products(self):
212 if not self.catalog:
213 print("No products available.")
214 for product in self.catalog.values():
215 print(product.display_details())
216
217
218 # -------------------- Main Console Interface --------------------
219 def main():
220 cart = ShoppingCart()
221
222 while True:
223 print("\n---- Online Shopping Cart ----")
224 print("1. View Products")
225 print("2. Add Item to Cart")
226 print("3. View Cart")
227 print("4. Update Quantity")
228 print("5. Remove Item")
229 print("6. Checkout (dummy)")
230 print("7. Exit")
231 choice = input("Choose an option: ")
232
233 if choice == "1":
234 cart.display_products()
235 elif choice == "2":
236 pid = input("Enter Product ID: ")
237 qty = int(input("Enter Quantity: "))
238 success = cart.add_item(pid, qty)
239 print("Added to cart!" if success else "Failed to add item.")
240 elif choice == "3":
241 cart.display_cart()
242 elif choice == "4":
243 pid = input("Enter Product ID: ")
244 qty = int(input("Enter new quantity: "))
245 success = cart.update_quantity(pid, qty)
246 print("Quantity updated." if success else "Failed to update.")
247 elif choice == "5":
248 pid = input("Enter Product ID: ")
249 success = cart.remove_item(pid)
250 print("Item removed." if success else "Item not found.")
251 elif choice == "6":
252 print(" Checkout complete. Thank you!")
253 break
254 elif choice == "7":
255 print("Exiting...")
256 break
257 else:
258 print("Invalid choice. Try again.")
259
260
261 if __name__ == "__main__":
262 main()
263
264

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy