3
while True:
    print "\n--------"
    room = getattr(self, next)
    next = room()

My question stems from the block of code above, found in Learn Python The Hard Way - Exercise 43. I understand that the third line stores the getattr() function results (in this case, self.next) into the room variable (unless I'm wrong there...?)

What is hanging me up right now is the fourth line, where the function room() is stored into the variable next. Fundamentally, I don't understand the room() part as this isn't a defined function in the code block. Does Python allow the user to define a function based on a preceding variable? (For example: writing room() for the first time creates a function called room() based on what is stored in the variable room).

Any help would be greatly appreciated!

Nathan
  • 4,009
  • 2
  • 20
  • 21
Arc'
  • 65
  • 1
  • 2
  • 4

1 Answers1

5
room = getattr(self, next)

Returns a function, which is then callable.

next = room()

Functions are first class objects in python, so they can be passed around as such. Handy!

Consider the following:

>>> class foo:
      def bar(self):
        print 'baz!'
      def __init__(self):
        # Following lines do the same thing!
        getattr(self, 'bar')()
        self.bar() 
>>> foo()
baz!
baz!
<__main__.foo instance at 0x02ADD8C8>
Aesthete
  • 18,622
  • 6
  • 36
  • 45
  • Thanks for the response and clearing that. I understand that gettr() returns a function and that they can be stored. But in the code above, no function is called, correct? The reason I ask is because in example 43 the next step in the coded story/game proceeds to be printed out. If you look at the code, how does the program move from the play() to central_corridor()? I'm used to seeing functions called through code simply as: self.central_corridor() instead of what play() provides (which I just see as functions being stored as opposed to being called). – Arc' Dec 09 '12 at 22:43
  • To clarify the above question: does next = room() run the room() function and store the results into the variable next? – Arc' Dec 09 '12 at 22:52
  • Yes that's exactly what is happening. – Aesthete Dec 10 '12 at 01:19
  • Hmm, interesting. Thanks for the response. – Arc' Dec 10 '12 at 01:43