0

In my program I have setup two classes called game.py and player.py. Both files call upon functions within the Player class (everything is imported properly), and in the game.py file all the information about the variables is printed. However, when a variable is updated from the Game class the new variable is printed fine, but when it is updated from the Player class it does not change. Instead, the variables printed are the ones from the init in the Player class.

For example

(in the Game class)
print player.health
player.health += 1
print player.health

will print

100
101

whereas if i were to do

self.health += 100 #(from within the Player class)

and then

print player.health #(from the Game class)

the output would be

100

note: the variables are being updated within the Player class but aren't being printed properly from the Game class. but I know they're being update in Player because the user still dies when health reaches 0 even though it's constantly displayed as 100

I believe the cause is the variables are all being reset to the init variables in the Player class, but that wouldn't fully explain why the Game class can manipulate the variables permanently. Does it have something to do with self.?

Any help is greatly appreciate. Thanks!

edit: Adding the code where Game gets the player variable

purple("\n\nHealth: %d" % player.health)

purple is a function that turns the text purple, player is defined at the start of the class as

player = Player()

it is no longer defined in any other file

9
  • Where is the Game code getting its player instance? Could it be modifying a different instance than your other code?
    – Blckknght
    Commented Mar 9, 2016 at 1:46
  • the Game code is importing the game.py file I have where Game is the only class Commented Mar 9, 2016 at 1:48
  • I just saw however that in the Game class and in the Main class I've created player = Player() in both, so maybe it's creating two instances of all the variables? Commented Mar 9, 2016 at 1:49
  • Yes, that would definitely do it. You probably want to create just one Player instance somewhere and pass it between your other objects (e.g. initialize Game by passing it a Player instance, perhaps).
    – Blckknght
    Commented Mar 9, 2016 at 1:51
  • I deleted the player = Player from the main file, so now there is only one instance of Player and it's in the Game class, yet still the problem persists Commented Mar 9, 2016 at 1:56

1 Answer 1

1

Python does not reset variables.

We can't know for sure what the problem is since you didn't show us the code where game acquires a player, but the evidence suggests that the player being updated with self.health += 100 is not the same player that game is using.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.