Implement a class Inventory
that maintains private lists of different product types (e.g. electronics, groceries, clothes). Implement methods for adding, removing, and fetching products, ensuring consistency and avoiding invalid states (like negative product quantities).
Example 1:
Input: Add 5 "electronics", Remove 2 "electronics" Output: Electronics: 3
Example 2:
Input: Add 3 "groceries", Remove 4 "groceries" Output: Invalid operation
Use private attributes to store the product quantities and provide public methods to modify them following the business rules.
class Inventory: def __init__(self): self._products = {'electronics': 0, 'groceries': 0, 'clothes': 0} def add_product(self, category, quantity): if category in self._products and quantity > 0: self._products[category] += quantity def remove_product(self, category, quantity): if category in self._products and 0 < quantity <= self._products[category]: self._products[category] -= quantity else: print("Invalid operation") def fetch_products(self, category): return self._products.get(category, "Category not found") # Test the class inventory = Inventory() inventory.add_product("electronics", 5) inventory.remove_product("electronics", 2) print(inventory.fetch_products("electronics")) # Output: 3 inventory.remove_product("groceries", 4) # Output: Invalid operation
Unlock AI & Data Science treasures. Log in!