Lesson 29 of 34 · Classes & OOP
Boss: Python OOP Inventory System
Gulpmaw the Mimic blocks the way. Every test you pass deals damage — pass them all to defeat it and claim a loot chest.
Gulpmaw the Mimic — a treasure chest with far too many teeth — has swallowed the Guild's supplies and won't give anything back until it knows exactly what it holds. Build it an inventory system with classes that behave like real Python objects — sized, searchable, printable and extensible — and the Mimic will open wide.
Battle plan
You'll combine a dataclass, a regular class with dunder methods, and a subclass that changes behaviour by overriding one method. That last trick is a classic design pattern: the base class calls self.weight_of(item) everywhere it needs a weight, so a subclass can change how weight is counted in exactly one place, and every other method automatically follows.
Assignment
1. Item — a dataclass with the fields name: str, weight: float and value: int.
2. Inventory(capacity) — stores capacity and a list items that starts empty. Methods:
weight_of(item)returns the weight this inventory counts for an item:item.weight.total_weight()returns the sum ofweight_of(item)over all items (0when empty).add(item)adds the item and returnsTrueif the total weight would stay within capacity (equal is fine); otherwise it leaves the inventory unchanged and returnsFalse.total_value()returns the sum of all item values.most_valuable()returns the item with the highest value, orNoneif the inventory is empty.__len__returns the number of items, solen(inventory)works.__contains__(name)returnsTrueif an item with that name is in the inventory, so"Rope" in inventoryworks.__str__returns"Inventory(<count> items, <weight>/<capacity> kg)"with weight and capacity shown with one decimal, e.g."Inventory(2 items, 3.5/10.0 kg)".
3. MagicInventory(Inventory) — a bag of holding where every item weighs half as much. Override only weight_of().
bag = Inventory(10)
bag.add(Item("Rope", 2.0, 5)) # True
bag.add(Item("Lantern", 1.5, 12)) # True
bag.add(Item("Anvil", 50.0, 30)) # False — too heavy
len(bag), "Rope" in bag # (2, True)
str(bag) # "Inventory(2 items, 3.5/10.0 kg)"
bag.most_valuable() # Item(name='Lantern', weight=1.5, value=12)Premium lesson
Unlock the full Learn Python course
- All 34 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Keep learning
Need a quick reminder? The Python cheat sheet has every topic of Learn Python on one page.
Lesson last updated on .