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
- Declare
LineItem. Its body needs at least one line, which the next step adds. - Add the constructor with
self,name,priceandquantity. It runs when the driver writesLineItem("Apple", 5, 3). - Store
nameinself.name. Withoutself.the value would vanish when the constructor ends. - Store
priceinself.price. - Store
quantityinself.quantity. Now a row remembers all three values. - Add
subtotal(self), level with__init__. - Return price times quantity from it, both read through
self. - Declare
CartbelowLineItem. It will hold many rows. - Add its constructor, taking only
self, because a new cart takes no values. - Create its storage: an empty list in
self._items. The underscore marks it as internal. - Add
add(self, item), whereitemis aLineItem. - Append
itemtoself._items. The list keeps rows in the order they came in. - Add
total(self), which works the total out each time it is asked. - Start a variable
totalat 0. That is the answer for an empty cart. - Loop over
self._itemswithfor item in self._items:, soitemtakes each row in turn. - Add the row's subtotal to
totalby callingitem.subtotal(). The row knows its own price and quantity. - Return
totalafter 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 nametotalis a local variable. It doesn't replace the method, which you still call ascart.total(). It is legal, though a name such asresultwould avoid any confusion. - The cart stores references.
addkeeps 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 rowLineItem("Tea", 4, 2)added twice gives a total of 16. After setting itsquantityto 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 of10.0. The driver wraps its totals inint(...)so whole-number totals print as75, and so a value such as10.0would print as10. - Method calls go through
self. Inside the classes, every attribute isself.something. Outside, it isitem.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
totalreturns the starting 0, which is why the accumulator starts at 0. - Returning inside the loop. If
return totalis indented under thefor, 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 = 0on every pass keeps only the last row. - Forgetting
self.in the constructor.price = priceonly sets a local name, andsubtotalthen fails with anAttributeError. - Calling the method without parentheses.
item.subtotalis the method object itself. Adding that to a number raises aTypeError. Writeitem.subtotal(). - Making the cart a line item.
Cartdoesn't inherit fromLineItem. It holds them in a list.
Key takeaways
- Composition means one object holds others. Here a
Cartholds a list ofLineItemobjects. - 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.
