Exercise · Final project · lesson 8 of 8
Exercise: inventory
Write the class Inventory, a warehouse that counts the units of each item. Keep the quantities in a dict, and create the attribute for it in __init__(self). The methods are these:
add(name, qty)putsqtyunits of the itemnameinto the warehouse;take(name, qty)takesqtyunits of the itemnameout of the warehouse;count(name)returns how many units of the item the warehouse holds;names()returns a list of the item names in alphabetical order.
The stub declares the exception OutOfStockError. If the warehouse holds fewer than qty units of the item name, take raises OutOfStockError and leaves the warehouse unchanged.
- after
add("apple", 5)andadd("apple", 3):count("apple")→8 - when
count("pear")is2:take("pear", 3)raisesOutOfStockError, andcount("pear")stays2 - after
add("pear", 2)andadd("apple", 5):names()→['apple', 'pear']
Constraints: qty is a positive integer; count returns 0 for an unknown item, and take raises OutOfStockError for one; an item taken out in full leaves the warehouse, and names no longer returns it.
Do not add extra imports unless the task says so explicitly.
Subscribe to take the course
The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.