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
Scott Simontacchi
2,071 PointsUsing get_next_monster() before we have defined it
Why is it that we can call get_next_monster() before we have defined it? In the video, you write:
self.monster = self.get_next_monster()
def get_next_monster(self):
...
I would have thought the method would need to be written before it can be used. Thanks for the clarification!
All the best, Scott
2 Answers
Steven Parker
243,656 PointsYou forgot to provide a link to the course video, or the complete context for your code snippet.
But I'd bet that the function is not being used (as in invoked) before it is defined. That top line is probably part of another definition, so it won't actually be executed until the function it is being defined in is itself invoked.
Scott Simontacchi
2,071 PointsYour insight is impressive, that is exactly what is happening! See below:
class Game:
def setup(self):
self.player = Character()
self.monsters = [
Goblin(),
Troll(),
Dragon()
]
self.monster = self.get_next_monster()
def get_next_monster(self):
try:
return self.monsters.pop(0)
except IndexError:
return None
I'm still a bit confused about it though... At the end of the file we call Game() to start the program and, if it runs from top to bottom, shouldn't self.monster need to get self.get_next_monster() before it knows what it is? Why doesn't it matter?
Thanks so much for your help!
Scott
Steven Parker
243,656 PointsSee comment attached to my answer
Steven Parker
243,656 PointsSteven Parker
243,656 PointsYou would have trouble if you tried to call Game at the top of the file.