7. Instance Methods
def level_up(self), has the first argument,
7.1. Regular Methods without parameters
game.level_up()calls the method
self.game_level += 1adds 1 to
game.level_up(), self is not written in the parentheses since it is automatically passed.
game = LevelGame(game_level=1).
level_up()method has been called via
game.level_up(), the second print statement outputs 2.
class LevelGame: def __init__(self, game_level): self.game_level = game_level def level_up(self): self.game_level += 1 game = LevelGame(game_level=1) print(game.game_level) game.level_up() print(game.game_level)
Check that print output above is 1, then 2.
Modify the level_up function in the previous example so that the level can’t go above 10. Hint: use the max function.
Modify the code so that the LevelGame.game_level starts at 10 then goes down by 1 when a level_down function is called.
Modify the level_down function in the previous example so that the level can’t go below 0. Hint: use the min function.
7.2. Regular Methods with parameters
game.set_speed(5)calls the method
set_speedto set the variable
game = SpeedGame(1)initializes the game speed to 1.
game.set_speed(5)sets the game speed to 5.
class SpeedGame: def __init__(self, game_speed): self.game_speed = game_speed def set_speed(self, game_speed): self.game_speed = game_speed game = SpeedGame(1) print(game.game_speed) game.set_speed(5) print(game.game_speed)
Modify the set_speed function so that any speed values passed in are limited to a maximum speed of 10. Hint: use the max function.
Modify the set_speed function so the speed must be between 0 and 10. Hint: use the min and max functions.