Project: shopping cart
Python · Unit 14: Modern classes
- Full plan
- Python
- Project
- 3 exercises
You're going to build a shopping cart. A Product has a name and a price, and a Line puts together a product with the quantity you're taking.
What a line costs isn't stored: it's worked out with a @property, so it always agrees with the quantity.
from dataclasses import dataclass
@dataclass
class Product:
name: str
price: int
@dataclass
class Line:
prod: Product
qty: int
@property
def subtotal(self):
pre = self.prod.price
return pre * self.qty
bread = Product("bread", 20)
print(Line(bread, 3).subtotal)Prints
60
The rest of the explanation is in the lesson, which is part of the full plan.
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Complete the code
Three loaves of bread at 20. Complete it so it prints 60.
2. Write the code
Write the three methods of
Cart.add(prod, qty): store a newLineinself.lines.total: a@propertythat adds up the subtotals.__len__: how many lines the cart has.simulateis already written and returns both things.3. Write the code
Write
to_pay(c, shipping): it returns the cart's total plus what that shipping costs, but if the total reaches 500 the shipping isn't charged.simulatebuilds the cart and picks the shipping by its value.
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.