Deviopath › Python

Shopping Cart with a Dataclass

Medium · Dataclasses

The @dataclass decorator writes __init__, __repr__ and __eq__ for you from the class annotations. A field with a default value (qty: int = 1) must come after the fields without one. You can still add normal methods.

Turn Item into a dataclass with the fields name (str), price_cents (int) and qty (int, default 1), and add a method total() that returns price_cents * qty. Then write cart_total(items) that returns the sum of total() over a list of items (0 for an empty list).

The driver run_cart is already written: it builds Item objects from the rows and returns their repr and your total.

Next: Money with __repr__ and __eq__