Skip to the content

Project: shopping cart

Python · Unit 14: Modern classes

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. 1. Complete the code

    Three loaves of bread at 20. Complete it so it prints 60.

  2. 2. Write the code

    Write the three methods of Cart. add(prod, qty): store a new Line in self.lines. total: a @property that adds up the subtotals. __len__: how many lines the cart has. simulate is already written and returns both things.

  3. 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. simulate builds the cart and picks the shipping by its value.

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →