Part 6 mini-project: Inventory System
This project uses chapters 26 and 27: classes, __init__,
instance methods, and inheritance. Item and
Inventory manage a bag of loot.
What to build
Two classes in the same module file:
Item — one collectable thing.
Item(name, weight, value)— constructor.- Fields:
name(string),weight(number),value(number). describe()— one-line summary, e.g."sword (3.5kg, 50g)".
Inventory — a container of items.
Inventory()— constructor; starts with an empty list.- Field:
items(a list ofIteminstances). add(item)— append an item.remove(name)— remove the first item with that name; returns it, orNoneif none matches.list()— print each item'sdescribe()on its own line, then a totals footer.total_weight()— sum of weights.total_value()— sum of values.
main.py:
- Creates a few items.
- Creates an inventory and adds them.
- Lists the inventory.
- Removes one item by name.
- Lists again.
- Prints total weight and value as a summary.
A sample run:
Inventory (3 items):
- sword (3.5kg, 50g)
- shield (5.0kg, 30g)
- potion (0.2kg, 5g)
Totals: 8.70kg, 85g
(removed sword)
Inventory (2 items):
- shield (5.0kg, 30g)
- potion (0.2kg, 5g)
Totals: 5.20kg, 35g
File layout
Two files. As in Part 5, cd into the project folder
first:
cd projects/05-inventory/starter
python main.py
Files (in both starter/ and finished/):
inventory.py— definesItemandInventoryas Python classes. Both classes live at the top level; no special export step is needed.main.py— imports both classes and runs the scenario:from inventory import Item, Inventory
Hints
- Both classes use
__init__to set their fields onself. Inventory.remove(name)walksself.itemswithenumeratelooking for a matchingname, thenself.items.pop(i)drops it.- Use an f-string for the totals line in
Inventory.list:f"Totals: {self.total_weight():.2f}kg, {self.total_value()}g". Item.describecan return the string rather than printing it, soInventory.listcontrols how each line is displayed.
What is fair game
Anything from Parts 2-6: variables, control flow, functions, modules, lists, dicts, classes, methods.
Done?
When the scenario runs cleanly from main.py, you're
done. Next: Chapter 31 — From Python to
other platforms.