我试图打破LPTHW的第43课以更好地理解它,并独立地运行每一件作品,我无法理解它为什么会回来
PS C:\Python> python ex43.py
Traceback (most recent call last):
File "ex43.py", line 67, in <module>
a_game.play()
File "ex43.py", line 17, in play
self.scene_map.opening_scene.enter()
AttributeError: 'function' object has no attribute 'enter'
我试图让它只是我的代码的第一个场景,然后最终打印出来“你已经进入了中央走廊&#39;这样我就能理解每个函数的调用方式。
from sys import exit
from random import randint
class Scene(object):
def enter(self):
print "This scene is not yet configured. Subclass it and implement enter()."
exit(1)
class Engine(object):
def __init__(self, scene_map):
self.scene_map = scene_map
def play(self):
self.scene_map.opening_scene.enter()
class Death(Scene):
def enter(self):
pass
class CentralCorridor(Scene):
def enter(self):
print "You've entered the central corridor."
class LaserWeaponArmory(Scene):
def enter(self):
pass
class TheBridge(Scene):
def enter(self):
pass
class EscapePod(Scene):
def enter(self):
pass
class Map(object):
scenes = {
'central_corridor': CentralCorridor(),
'laser_weapon_armory': LaserWeaponArmory(),
'the_bridge': TheBridge(),
'escape_pod': EscapePod()
}
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.scene_map.opening_scene.enter(self.start_scene)
a_map = Map('central_corridor')
a_game = Engine(a_map)
a_game.play()
运行时会出现上述错误。我想我很难看到如何玩#&#39;正在启动&#39; opening_scene&#39;
答案 0 :(得分:0)
那是因为python中的所有函数如果你想调用它们,执行它们,你必须使用()
所以你的代码应该是:
class Engine(object):
def __init__(self, scene_map):
self.scene_map = scene_map
def play(self):
self.scene_map.opening_scene().enter()
或者只是:
def play(self):
self.scene_map.opening_scene()
答案 1 :(得分:0)
能够通过这个帖子找到答案:r/learnpython
基本上,我正在打电话给他们开放式的&#39;在opens_scene&#39;而我必须通过return self.scenes[self.start_scene].enter()
通过a.game.play()调用传递给Map的场景,这将运行&#39; enter()&#39;无论它通过什么场景。由于开场场景设置为“中央走廊”。这是它从词典中拉出来的东西。我希望这是有道理的,并不像它感觉那样脱节。