Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Object-Oriented Python (retired) Hack-n-Slash The Final Push

Edrei Garcia
Edrei Garcia
1,419 Points

In game.py, why does __init__ execute?

Hello,

In the script game.py, we just call the class Game(), we don't create an instance of it... so why does the init method execute?

Also, if we didn't create an instance, why do we need the self parameter or who/what is self if not an instance?

I wasn't really sure how to explain my confusion, so if you need more info, please ask!

Thanks all!

2 Answers

Michael Hulet
Michael Hulet
47,913 Points

When you "call a class" (as you describe it), what you're doing is creating an instance of it, and every time an instance of a class is created, the __init__ method is run

Edrei Garcia
Edrei Garcia
1,419 Points

Ahh, I see. So does that instance get a name? Without knowing the name of that instance, how do I see the attribute values of that instance?

Michael Hulet
Michael Hulet
47,913 Points

In this case, it doesn't, but it doesn't need to. The game is entirely executed when the instance is created. If you want to assign it to a variable, though, you can, but you will never get to access it, because the game never ends (If I remember correctly, you just continually play again when you lose, but it's been a while since I've taken this course)

Edrei Garcia
Edrei Garcia
1,419 Points

That's true but I went ahead and commented out the game loop just to try this. I was trying to view the experience of the monster I was fighting by trying something like this: unknowgameinstance.monster.experience

Michael Hulet
Michael Hulet
47,913 Points

You should be able to assign it to a variable and refer to it through the variable, like this:

inspectableGame = Game()
print(inspectableGame.monster.experience)