6. Class variables
6.1. Class variables common to instances
game_level
is a class variable.game1.game_level
and game2.game_level
have the same value.class LevelGame:
game_level = 1
game1 = LevelGame()
print(game1.game_level)
game2 = LevelGame()
print(game2.game_level)
Tasks
Check that the print output is the same for each print statement above.
Modify the code so that the class definition has a game_level of 0, then check its value for both instances.
6.2. Changing Class variables for all instances
LevelGame.game_level = 3
, the class variable is changed to 3.game1.game_level
and game2.game_level
.class LevelGame:
game_level = 1
game1 = LevelGame()
game2 = LevelGame()
LevelGame.game_level = 3
print(game1.game_level)
print(game2.game_level)
Tasks
Check that print output is the same for each statement above.
Modify the code so that the LevelGame.game_level is set to 5, then check its value for both instances.
6.3. Changing Class variables in an instance
game.game_level = 2
changes the value of the variable within the instance.LevelGame.game_level
is not altered.class LevelGame:
game_level = 1
game = LevelGame()
game.game_level = 2
print(game.game_level)
print(LevelGame.game_level)
Tasks
Check the print output to verify that the instance has a different value to the class.
Add code after the instance value is changed so that the
LevelGame.game_level
is set to 5, then check the value for the instance to see if it is affected.
Tip
Use Class variables when the same value is needed in all instances.
Avoid changing class variables in instances since it can lead to confusion.
Use Instance variables instead of class variables when different values are needed in each instance.
6.4. Modifying Class variables during instantiation
game_number
is a class variable.LevelGame.game_number += 1
is used to increment the game number by 1 each time a new LevelGame is instantiated.game_number
is a class variable, it is accessed via LevelGame.game_number
within the __init__ function. The class name, LevelGame
is used instead of self.class LevelGame:
game_number = 0
def __init__(self, game_level):
self.game_level = game_level
LevelGame.game_number += 1
game = LevelGame(1)
print(game.game_number)
game2 = LevelGame(2)
print(game.game_number)
print(game2.game_number)
Tasks
Check that print output shows that the class variable is the same for both instances.
Add a third instance, game3, then check the class variable value for all three instances.