5. The init method
5.1. The __init__() method
__init__()method is a built-in-method that is used to assign values to object attributes, and to do other operations that are necessary when the object is created.
__init__()function is called automatically every time the class is called when creating a new object.
__init__()function is self, referring to the object itself.
level, are passed in as arguments when the class is called.
game = LevelGame(level=1)passes in
game = LevelGame(1)and
game = LevelGame(level=1)do the same thing.
game = LevelGame(level=1, lives=3)passes in
class LevelGame: def __init__(self, game_level, player_lives): self.game_level = game_level self.player_lives = player_lives game = LevelGame(game_level=1, player_lives=3)
Modify the code so that the game level starts at level 0 with 5 lives.
Modify the code so the parameters and the instance variables have matching names.
Modify the code by adding a third instance variable using a parameter called level_score and initialize it to 0.
*args in the __init__() function
*argscan be used for the parameter.
*argspacks all the arguments into one single variable that can be treated like a normal tuple.
enemies = Enemies(1, 2, 3)instantiates Enemies with 3 different enemies_levels.
class Enemies: def __init__(self, *args): self.enemy_levels = args enemies = Enemies(1, 2, 3) print(enemies.enemy_levels)
Test the Enemies example above by printing the enemy levels using the instance attribute for the enemy_levels.