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

Why does the method get_next_monster() not need to be defined above where it is called?

While planning for the monster game, Kenneth defines the Game class and defines the first method setup. Inside setup, self.monster = to self.get_next_monster(). However, get_next_monster is not defined before it is called on in the next line.

In python, how does this work? In C, there aren't objects. However the function must be defined before it's called.

self.monster = [
      Goblin(),
      Troll(),
      Dragon()
    ]
    self.monster = self.get_next_monster()

 def get_next_monster(self):

    try:
      return self.monsters.pop(0)     
    except IndexError:
      return None

1 Answer

The Python interpreter is capable of look ahead when dealing with method/function names so you don't need to restrict their ordering:

def first():
  print("first")
  last()

def last():
  print("last")

class Order(object):
  def __init__(self):
    print("__init__")
    self.setup()

  def setup(self):
    print("setup")

first()
Order()

The best you could do with C (if I'm remembering this correctly) is forward declaration:

#include <stdio.h>
#include <stdlib.h>

void helloWorld();

int main(void)
{
    helloWorld();

    return EXIT_SUCCESS;
}

void helloWorld()
{
    puts("Hello World!");
}