Advertisement
SimeonTs

SUPyF2 Objects/Classes-Exericse - 02. Weapon

Oct 19th, 2019
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.38 KB | None | 0 0
  1. """
  2. Objects and Classes - Exericse
  3. Check your code: https://judge.softuni.bg/Contests/Practice/Index/1734#1
  4.  
  5. SUPyF2 Objects/Classes-Exericse - 02. Weapon
  6.  
  7.  
  8. Problem:
  9. Create a class Weapon. The __init__ method should receive an amount of bullets (integer).
  10. The class should also have the following methods:
  11. • shoot() - if there are bullets in the weapon, reduce them by 1 and return a message "shooting…".
  12. If there are no bullets left, return: "no bullets left"
  13. You should also override the toString method, so that the following code: print(weapon) should work.
  14. To do that define a __repr__ method that returns "Remaining bullets: {amount_of_bullets}".
  15. You can read more about the __repr__ method here: link
  16.  
  17. Example:
  18.  
  19. Test Code:
  20. weapon = Weapon(5)
  21. weapon.shoot()
  22. weapon.shoot()
  23. weapon.shoot()
  24. weapon.shoot()
  25. weapon.shoot()
  26. weapon.shoot()
  27. print(weapon)
  28.  
  29. Output:
  30. ['apple', 'banana', 'potato', 'tomato']
  31. """
  32.  
  33.  
  34. class Weapon:
  35.     def __init__(self, bullets: int):
  36.         self.bullets = bullets
  37.  
  38.     def shoot(self):
  39.         if self.bullets > 0:
  40.             self.bullets -= 1
  41.             return f"shooting..."
  42.         else:
  43.             return f"no bullets left"
  44.  
  45.     def __str__(self):
  46.         return f"Remaining bullets: {self.bullets}"
  47.  
  48.  
  49. weapon = Weapon(5)
  50. weapon.shoot()
  51. weapon.shoot()
  52. weapon.shoot()
  53. weapon.shoot()
  54. weapon.shoot()
  55. weapon.shoot()
  56. print(weapon)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement