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!
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
fahad lashari7,693 Points
Why was the while loop that runs the game implemented into the def __init__() function?
Although I generally do understand that init function is something that is automatically called when the instance of the class is created. Isn't this function normally used for setting attributes. Or is this something like the 'main' function from Java where upon running the programme, this code is the first part that is executed.
Can init be used for anything when you just want to run a specific piece of code first? Could someone please explain this part to me. Apologies if there is an obvious answer. I am a novice at Python and programming in general.
Steven Parker228,038 Points
Remember to "think in Python".
One of the first things I learned about Python is to not compare it to other languages and design patterns. There's the "Python way" and then there's everything else. To really do Python well, (or easily!) you have to "think in Python".
In this case, the Game.init function is operating much like a "main" since the class encapsulates the main program functionality. But unlike a "main", the class is explicitly instantiated later in the file. But classes don't always (perhaps not even often) encapsulate program functionality, so the
__init__ function might just be used for setting attributes in other cases.
__init__ it is basically available for any purpose where you want something done on instantiation.
__init__ Is a special function that is always called if you create a new instance of the class the
__init__ function is in.
Kenneth actually created a new instance of the class at the bottom of the file, that's why the
__init__ function is called. :)
I hope you get it. ~Alex