Great demonstration of the problem! You’ve hit on what’s going on and made a good summary. Thank you for helping us to help you
So the crucial difference is between these two blocks:
s = Score()
When you call Score(), what you’re doing is constructing a Score object (also called “instantiating the Score class”). Each time you do that, you get a completely new Score object with no memory of the previous ones. For the first example, you create one single Score object, then set three things on it, and finally retrieve those three from it; in the second, you construct six indepented Score objects - three of them get something set on them and then the object gets discarded, and the other three are built just to look up something, and are then discarded.
You can make use of this if you want to! Imagine you had a two-player game. You could…
player_one = Score()
player_two = Score()
and then update their scores and lives independently.
s = Score() creates an instance and binds it to s. You then call some of its methods that modify attributes.
Score().set_score(100) creates an instance and calls a method on it. The instance is then discarded. Score().set_enemies(200) creates an instance and calls a method on it. The instance is then discarded.
2 separate instances, both have an attribute modified, both discarded.
Chris & Mathew…
Thank you very much. I’ve read the python documentation on classes so your explanations make perfect sense. I just couldn’t get my head around just what was going on with regard to the instantiation. Appreciate your quick responses.