Python 2.7中Game类的next变量与程序流程疑问求助
Hey there! Let's break down your questions one by one, since you're working through Zed's book (great choice for building foundational skills, by the way) and hitting a couple of roadblocks with that code.
next a special keyword in Python 2.7? Short answer: No, next isn't a reserved keyword in Python 2.7. Your editor is highlighting it blue because it's a built-in function in Python 2.7—this function is used to retrieve the next item from an iterator.
While using next as a variable name won't throw an error, it's not a great practice: it overrides the built-in function within that scope, which can lead to confusion or bugs later if you try to use the actual next() function. It's better to rename it to something like next_room or current_room to keep things clear.
Let's trace the code starting from next = self.start to make sense of how this game loop works:
1. First, the game gets initialized
When you run a_game = Game("central_corridor"):
- The
__init__method runs, settingself.start = "central_corridor"and initializing theself.quipslist of funny death messages. - You now have a
Gameinstance calleda_gamethat knows its starting point is thecentral_corridormethod.
2. Starting the game with a_game.play()
Once you call play(), here's what happens line by line:
next = self.start: This sets the variablenextto the string"central_corridor"—this is the name of the first room method we'll run.- The
while Trueloop starts (this will run forever until we hitexit(0)in thedeathmethod).print "\n-------": Just prints a separator line for readability.room = getattr(self, next): Thegetattr()function looks up an attribute (or method) on thea_gameinstance using the string stored innext. Sincenextis"central_corridor", this grabs thecentral_corridor()method of theGameclass.next = room(): This calls thecentral_corridor()method. What happens here depends on the code you omitted ([ some other functions ]), but the key thing is: this method should return a string that's the name of another room method (like"death"or maybe"laser_weapon_armory"if you follow the book's full example). That returned string becomes the new value ofnext, so the loop will run that room method next.
3. What happens if we hit the death method?
If at any point a room method returns "death", the next loop iteration will:
- Use
getattr(self, "death")to grab thedeath()method. - Call
death(), which picks a random quip fromself.quips, prints it, and runsexit(0)—this terminates the program immediately, ending the loop.
Think of this as a state machine: each room method is a "state", and returning a room name string tells the game loop which state to move to next. It's a clever way to build a text-based game without writing tons of nested conditionals!
内容的提问来源于stack exchange,提问作者Minh Truong

