Advertisement
SimeonTs

SUPyF2 Objects/Classes-Exericse - 06. Inventory

Oct 19th, 2019
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.73 KB | None | 0 0
  1. """
  2. Objects and Classes - Exericse
  3. Check your code: https://judge.softuni.bg/Contests/Practice/Index/1734#5
  4.  
  5. SUPyF2 Objects/Classes-Exericse - 06. Inventory
  6.  
  7. Problem:
  8. Create a class Inventory. The __init__ method should accept only the capacity of the inventory.
  9. The capacity should be a private attribute (__capacity). You can read more about private attributes here.
  10. Each inventory should also have an attribute called items, where all the items will be stored.
  11. The class should also have 3 methods:
  12. • add_item(item) - adds the item in the inventory if there is space for it. Otherwise, returns
  13. "not enough room in the inventory"
  14. • get_capacity() - returns the value of __capacity
  15. • __repr__() - returns "Items: {items}. Capacity left: {left_capacity}". The items should be separated by ", "
  16.  
  17. Examples:
  18. Test Code:
  19. inventory = Inventory(2)
  20. inventory.add_item("potion")
  21. inventory.add_item("sword")
  22. inventory.add_item("bottle")
  23. print(inventory.get_capacity())
  24. print(inventory)
  25.  
  26. Output:
  27. not enough room in the inventory
  28. 2
  29. Items: potion, sword.
  30. Capacity left: 0
  31. """
  32.  
  33.  
  34. class Inventory:
  35.     def __init__(self, capacity):
  36.         self.__capacity = capacity
  37.         self.items = []
  38.  
  39.     def add_item(self, item):
  40.         if len(self.items) < self.__capacity:
  41.             self.items.append(item)
  42.             return
  43.         return f"not enough room in the inventory"
  44.  
  45.     def get_capacity(self):
  46.         return self.__capacity
  47.  
  48.     def __repr__(self):
  49.         return f"Items: {', '.join(self.items)}.\nCapacity left: {self.__capacity - len(self.items)}"
  50.  
  51.  
  52. inventory = Inventory(2)
  53. inventory.add_item("potion")
  54. inventory.add_item("sword")
  55. inventory.add_item("bottle")
  56. print(inventory.get_capacity())
  57. print(inventory)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement