我开始根据本书作者的骨架创建一个简单的应用程序。我不明白为什么在下面的代码中,类enter
的方法Start
没有运行,而类enter
的方法The_end
会运行。你能解释一下吗?
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from sys import exit
class Engine(object):
def __init__(self, scene_map):
self.scene_map = scene_map
def play(self):
current_scene = self.scene_map.opening_scene()
last_scene = self.scene_map.next_scene('the_end')
while current_scene != last_scene:
next_scene_name = current_scene.enter()
current_scene = self.scene_map.next_scene(next_scene_name)
current_scene.enter()
class Scene(object):
def enter(self):
print "not configured yet"
exit(1)
class Start(Scene):
def enter(self):
print "Enter your name: "
name = raw_input(" ")
print "Hi %s. How old are you?" % (name)
age = raw_input( )
if age < 18:
print "Sorry %s... You're too young to play this game." % (name)
return 'the_end'
elif age >= 18:
print "Excellent %s! We can continue! Press enter" % (name)
raw_input()
print """Ok %s... I can tell you that it's not a comfortable situation.
You've lost your memory so here's what happend.
Today you were eating breakfast on your terrace and suddenly some alien showed from nowhere.
It has minimized you with its odd gun so now your size is like a match box - more or less.
Furthermore, the alien has teleported you - you are in some unknown empty house.
You have to get yourself out in order to come back home, find the alien
and bring back your initial size.""" % (name)
raw_input()
class The_end(Scene):
print "you're dead"
exit(1)
class Map(object):
scenes = {
"start": Start(),
"the_end": The_end(),
}
def __init__(self, start_scene):
self.start_scene = start_scene
def next_scene(self, scene_name):
val = Map.scenes.get(scene_name)
return val
def opening_scene(self):
return self.next_scene(self.start_scene)
a_map = Map("start")
a_game = Engine(a_map)
a_game.play()
答案 0 :(得分:3)
这将在您运行程序时首先执行:
class The_end(Scene):
print "you're dead"
exit(1)
你可能想要这样的东西:
class The_end(Scene):
def enter(self):
print "you're dead"
exit(1)
您在类级别定义的所有内容(对于在模块级别定义的类)将在Python通过这些行时立即执行。导入具有类级代码的模块时也会发生这种情况。