Start learning free

LESSON 66 OF 69 · PROJECTS: OBJECT-ORIENTED

Shopping Cart in Python: LineItem and Cart Classes

Practice Read the full explanation

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 in self.name, self.price and self.quantity.
  • subtotal(self) returns price * quantity, the money this one row adds up to.

Cart

  • __init__(self) creates an empty list in self._items (the leading underscore means: internal, don't touch it from outside).
  • add(self, item) appends a LineItem to the list.
  • total(self) returns the sum of the subtotals of all items. Use a plain loop: start with total = 0, add each item.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())))

STEP 1 OF 17
    Ctrl + Enter to check

    PYTHON · PROJECTS: OBJECT-ORIENTED

    Shopping Cart in Python, explained

    Problem overview

    A shop keeps orders in a cart, and you build the two classes that model it. A LineItem is one row of the cart: a product name, a price and a quantity. A Cart holds many rows and adds them up. The cart has line items, so this is composition: Cart stores LineItem objects and isn't one.

    LineItem needs __init__(self, name, price, quantity), which stores the three values in self.name, self.price and self.quantity, and subtotal(self), which returns price times quantity. Cart needs __init__(self) with an empty list in self._items, add(self, item) to append a row and total(self) to sum the subtotals.

    The driver checks an empty cart, then an Apple row with price 5 and quantity 3 (subtotal 15), then a cart holding the Apple and 3 Bread at 20 (total 75), then adds 2 Milk at 10 and prints the total again, 95.

    Approach: each object does its own part

    The design gives each class one job. A LineItem knows how much its own row costs, because it holds both numbers. The Cart doesn't multiply prices itself. It asks each row for its subtotal and adds the answers. If rows ever need a discount, only LineItem changes and Cart.total stays as it is.

    The total is not stored. total recomputes it every time from the rows that are in the cart at that moment, so adding an item changes the next total without extra bookkeeping. There is no running total that could drift out of date. An empty cart has no rows to add, so the loop does nothing and the total is the starting value, 0.

    The lesson asks for a plain loop: start a variable at 0, add each item.subtotal() and return it. Python's sum could shorten this, but the loop makes the accumulator pattern visible.

    Step by step

    1. Declare LineItem. Its body needs at least one line, which the next step adds.
    2. Add the constructor with self, name, price and quantity. It runs when the driver writes LineItem("Apple", 5, 3).
    3. Store name in self.name. Without self. the value would vanish when the constructor ends.
    4. Store price in self.price.
    5. Store quantity in self.quantity. Now a row remembers all three values.
    6. Add subtotal(self), level with __init__.
    7. Return price times quantity from it, both read through self.
    8. Declare Cart below LineItem. It will hold many rows.
    9. Add its constructor, taking only self, because a new cart takes no values.
    10. Create its storage: an empty list in self._items. The underscore marks it as internal.
    11. Add add(self, item), where item is a LineItem.
    12. Append item to self._items. The list keeps rows in the order they came in.
    13. Add total(self), which works the total out each time it is asked.
    14. Start a variable total at 0. That is the answer for an empty cart.
    15. Loop over self._items with for item in self._items:, so item takes each row in turn.
    16. Add the row's subtotal to total by calling item.subtotal(). The row knows its own price and quantity.
    17. Return total after the loop, with no extra indent, so it runs once after every row has been added.

    The solution in Python

    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())))
    

    Python details worth a look

    • A local variable named like the method. Inside total, the name total is a local variable. It doesn't replace the method, which you still call as cart.total(). It is legal, though a name such as result would avoid any confusion.
    • The cart stores references. add keeps the same object the caller gave it, not a copy. If the caller changes that object later, the next total changes too. For example, a row LineItem("Tea", 4, 2) added twice gives a total of 16. After setting its quantity to 5, the total is 40.
    • Numbers aren't converted. The class works with whatever numbers it receives. A row LineItem("Pen", 2.5, 4) has a subtotal of 10.0. The driver wraps its totals in int(...) so whole-number totals print as 75, and so a value such as 10.0 would print as 10.
    • Method calls go through self. Inside the classes, every attribute is self.something. Outside, it is item.subtotal().

    What the driver prints

    Empty: 0
    Subtotal: 15
    Total: 75
    Total: 95
    

    Bread contributes 20 times 3, which is 60, and the Apple row 15, so the first total is 75. Milk adds 10 times 2, which is 20, so the second total is 95.

    Complexity

    subtotal and add run in O(1). total visits every row once, so it takes O(n) for n rows, and it is paid on every call because nothing is cached. The cart's list uses O(n) space.

    Edge cases and common mistakes

    • An empty cart. The loop never runs and total returns the starting 0, which is why the accumulator starts at 0.
    • Returning inside the loop. If return total is indented under the for, the method returns after the first row. In the driver's cart that would print 15 instead of 75.
    • Starting the accumulator inside the loop. Resetting total = 0 on every pass keeps only the last row.
    • Forgetting self. in the constructor. price = price only sets a local name, and subtotal then fails with an AttributeError.
    • Calling the method without parentheses. item.subtotal is the method object itself. Adding that to a number raises a TypeError. Write item.subtotal().
    • Making the cart a line item. Cart doesn't inherit from LineItem. It holds them in a list.

    Key takeaways

    • Composition means one object holds others. Here a Cart holds a list of LineItem objects.
    • Let each object compute what it knows. The row calculates its subtotal and the cart only adds.
    • Computing the total on demand keeps it correct when items are added later.
    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free