[英]on classes and attributes python
我正在研究一个教程,其中它在python上创建了一个基于文本的游戏,以练习使用类和属性。
基本结构是Scene将是超类,引擎将运行以进入下一个场景。
我在理解命令的后三行如何工作时遇到了麻烦。
据我了解。
a_map = Map('central_corridor')
创建该类的一个实例Map
它运行__init__
在功能Map
从而打印start_scene in __init__ central corridor
。
然后a_game = Engine(a_map)
创建的实例Engine
并运行__init__
的Engine
从而打印Engine __init__ has scene map, scene_map
现在我不明白要打印的最后一部分
start_scene in opening_scene
start_scene in next_scene
next_scene returns _____
然后它运行a_game.play()
如果您能解释一下两者之间发生的事情,那将是很好的。
from sys import exit
from random import randint
class Scene(object):
def enter(self):
pass
class Engine(object):
def __init__(self, scene_map):
print "Engine __init__ has scene map", scene_map
self.scene_map = scene_map`
def play(self):
current_scene = self.scene_map.opening_scene()
print "Plays first scene", current_scene
while True:
print "\n------------"
next_scene_name = current_scene.enter()
print "next scene", next_scene_name
current_scene = self.scene_map.next_scene(next_scene_name)
class CentralCorridor(Scene):
pass
class LaserWeaponArmory(Scene):
pass
class Bridge(Scene):
pass
class EscapePod(Scene):
pass
class Death(Scene):
pass
class Map(object):
scenes = {
'central_corridor' : CentralCorridor(),
'laserweaponarmory' : LaserWeaponArmory(),
'Bridge' : Bridge(),
'escape_pod' : EscapePod(),
'Death' : Death()
}
def __init__(self, start_scene):
self.start_scene = start_scene
print "start_scene in __init__", self.start_scene
def next_scene(self, scene_name):
print "start_scene in next_scene"
val = Map.scenes.get(scene_name)
print "next_scene returns", val
return val
def opening_scene(self):
print "start_scene in opening_scene"
return self.next_scene(self.start_scene)
a_map = Map('central_corridor')
a_game = Engine(a_map)
a_game.play()
澄清:
start_scene in opening_scene
start_scene in next_scene
next_scene returns _____
并且由于运行
a_game.play()
引擎和地图如下所示:
Engine
- scene_map <- Scene
- start_scene <- String
+ __init__()
+ next_scene()
+ opening_scene()
Map
- start_scene <- String
- scenes <- Dictionary of Scene
+ __init__()
+ play()
play()在scene_map上调用opening_scene():
self.scene_map.opening_scene()
opening_scene()使用“ central_corridor”调用next_scene()
self.next_scene(self.start_scene)
next_scene()使用传入的键“ central_corridor”在场景字典中查找相关场景。
Map.scenes.get(scene_name)
通过方法调用链返回场景,并将其存储在current_scene中
current_scene = self.scene_map.opening_scene()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.