A shop keeps its orders in a cart. Build two classes that work together: a LineItem is one row of the cart (a product, its price and how many were bought), and a Cart holds many rows and adds them up. The cart has line items (composition), it is not one.
LineItem
__init__(self, name, price, quantity)stores the three values inself.name,self.priceandself.quantity.subtotal(self)returnsprice * quantity, the money this one row adds up to.
Cart
__init__(self)creates an empty list inself._items(the leading underscore means: internal, don't touch it from outside).add(self, item)appends aLineItemto the list.total(self)returns the sum of the subtotals of all items. Use a plain loop: start withtotal = 0, add eachitem.subtotal(), then return it.
Rules:
- The total is worked out every time it is asked for, from the items in the cart at that moment. Adding an item later changes the next total.
- An empty cart has a total of
0. - An item with price 5 and quantity 3 has a subtotal of 15.
- Prices in the driver are whole numbers.
The driver wraps the numbers in int(...) so a whole-number total prints as 75.
The driver (already in the starter code, don't change it) creates an empty cart, checks one subtotal, then fills a cart and prints the total twice:
cart = Cart()
cart.add(apple)
cart.add(LineItem("Bread", 20, 3))
print("Total: " + str(int(cart.total())))
cart.add(LineItem("Milk", 10, 2))
print("Total: " + str(int(cart.total())))
Expected output:
Empty: 0 Subtotal: 15 Total: 75 Total: 95
Start with
class LineItem: and its __init__, then subtotal. Then class Cart: with the list in __init__.
For
total: total = 0, then for item in self._items: add item.subtotal() to it, then return total.
class LineItem:
def __init__(self, name, price, quantity):
self.name = name
self.price = price
self.quantity = quantity
def subtotal(self):
return self.price * self.quantity
class Cart:
def __init__(self):
self._items = []
def add(self, item):
self._items.append(item)
def total(self):
total = 0
for item in self._items:
total += item.subtotal()
return total
empty = Cart()
print("Empty: " + str(int(empty.total())))
apple = LineItem("Apple", 5, 3)
print("Subtotal: " + str(int(apple.subtotal())))
cart = Cart()
cart.add(apple)
cart.add(LineItem("Bread", 20, 3))
print("Total: " + str(int(cart.total())))
cart.add(LineItem("Milk", 10, 2))
print("Total: " + str(int(cart.total())))
Free plan: 30 tutor messages. Premium is unlimited.
