Foundation project
Project: an inventory manager
Lesson 12 of 20 · 20 min · Module 3: Objects that behave
Combine classes, dictionaries, validation, and properties to build the core of a small shop’s inventory system.
Start this lesson →Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Design a class around one internal data structure
- Validate before changing state
- Provide read-only views with properties
The idea
Keep the stock in a dictionary inside the object. Every method either changes the stock safely or reports on it. Invalid operations raise ValueError with a clear message and leave the stock unchanged.
stock = {"apples": 5}
stock["apples"] = stock.get("apples", 0) + 3
print(stock)
01Hide the data, expose behaviour
The dictionary lives in self._stock. Callers use add, remove, and report, so the rules (no negative stock, no zero entries) are enforced in one place.
02Validate first, change second
If remove checked the quantity after subtracting, a failed call could leave the stock broken. Checking every condition before touching the dict keeps the object consistent even when errors happen.
inv = Inventory()
inv.add("ink", 2)
try:
inv.remove("ink", 5)
except ValueError as err:
print(err, inv.report())not enough ink ['ink: 2']03bool is an int
In Python, True == 1 and isinstance(True, int) is True. Explicitly rejecting bool stops add("x", True) from adding one unit by accident.
Your project brief
Inventory with:•
add(name, quantity): adds stock; quantity must be a positive integer, otherwise raise ValueError;•
remove(name, quantity): removes stock; raise ValueError if the item is unknown or there is not enough; remove the item entirely when it reaches 0;• a
total property with the total number of units;•
low_stock(threshold): sorted names with quantity below threshold;•
report(): lines "apples: 5" sorted by name.What the checks look for
- Adds stock and reports it sorted
- Removes stock and deletes items that reach zero
- Rejects invalid quantities
- Rejects removing unknown or insufficient stock without changing anything
- Calculates the total and low stock
Take this with you
A good class protects its own rules: check, then change.
Go a little further
Add a history list that records every successful add and remove, and a method that undoes the last change.