J
unknown
javascript
3 years ago
1.6 kB
9
Indexable
class Product:
def __init__(self, name, price, quantity):
self.name = name
self.price = price
self.quantity = quantity
def __str__(self):
return f'{self.name} - ${self.price} ({self.quantity} available)'
class Shop:
def __init__(self):
self.products = []
def add_product(self, product):
self.products.append(product)
def display_products(self):
for product in self.products:
print(product)
def search_product(self, name):
for product in self.products:
if product.name == name:
return product
return None
class Cart:
def __init__(self):
self.items = []
def add_item(self, product, quantity):
self.items.append((product, quantity))
def remove_item(self, product):
self.items.remove(product)
def display_cart(self):
total_price = 0
for item in self.items:
product, quantity = item
price = product.price * quantity
print(f'{product.name} x{quantity} - ${price}')
total_price += price
print(f'Total: ${total_price}')
# Create some products
apple = Product('Apple', 1.0, 10)
banana = Product('Banana', 0.5, 20)
carrot = Product('Carrot', 0.3, 30)
# Create a shop and add the products
shop = Shop()
shop.add_product(apple)
shop.add_product(banana)
shop.add_product(carrot)
# Create a cart and add some items
cart = Cart()
cart.add_item(apple, 3)
cart.add_item(banana, 5)
# Display the products and cart
shop.display_products()
cart.display_cart()
Editor is loading...