我正在练习“学习Python艰难之路”中的练习43,尝试填写作者的骨架OOP代码,以便进行有效的冒险"打字游戏。在本文的最后几个练习之前,我从未做过任何OOP,所以这很难。
我在类中使用__init__
来创建提供" case"的字典。函数(因此它可用于类中的所有方法)通过存储键引用的调用(经典"使您自己的case语句"对于Python),但方法需要参数(以保持跟踪已经看到的房间,携带库存等) - 当我为参数包含变量时,我总是得到一个错误,即#34; [name]在赋值之前引用"或类似的。如果我提供空白或常量/文字参数,我不会得到错误,但显然如果参数不是变量,我的调用后来就无法正常工作。
如果我将dict def移动到Engine类的主方法中,一切看起来都很好,但是我必须在类中的每个方法中再次定义整个dict,对吧?这是我正在处理的课程,主要方法中的字典而不是__init__
- 如何将此字典放入__init__
并使其有效?< / p>
class Engine (object):
def __init__(self, scene_map):
self.scene_map = scene_map
def drop_item(self, c_list, inv, log):
pass
def goto(self, c_list, inv, log):
print c_list
pass
def take_item(self, c_list, inv, log):
pass
def inventory(self, c_list, inv, log):
pass
def show_items(self, c_list, inv, log):
pass
def set_bomb(self, c_list, inv, log):
pass
def talk_to(self, c_list, inv, log):
pass
def play(self):
next_move = []
stuff = []
seen = []
self.act = {
'drop' :self.drop_item(next_move, stuff, seen),
'enter' :self.goto(next_move, stuff, seen),
'get' :self.take_item(next_move, stuff, seen),
'go' :self.goto(next_move, stuff, seen),
'inventory' :self.inventory(next_move, stuff, seen),
'leave' :self.goto(next_move, stuff, seen),
'look' :self.show_items(next_move, stuff, seen),
'run' :self.goto(next_move, stuff, seen),
'start' :self.set_bomb(next_move, stuff, seen),
'take' :self.take_item(next_move, stuff, seen),
'tell' :self.talk_to(next_move, stuff, seen),
}
self.obj = {
'armory' :'',
'blaster' :'',
'bomb' :'',
'bridge' :'',
'cabin' :'',
'corridor':'',
'gangway' :'',
'gothon' :'',
'keypad' :'',
'pod' :'',
}
self.scene_map.opening_scene()
entry = UserEntry()
done = False
dead = False
while not done:
next_move = entry.get_input()
entry.obj [next_move (0)] (next_move)`
我试图得到更像这样的东西:
def __init__(self):
self.scene_map = scene_map
self.act = {
'drop' :self.drop_item(next_move, stuff, seen),
'enter' :self.goto(next_move, stuff, seen),
'get' :self.take_item(next_move, stuff, seen),
'go' :self.goto(next_move, stuff, seen),
'inventory' :self.inventory(next_move, stuff, seen),
'leave' :self.goto(next_move, stuff, seen),
'look' :self.show_items(next_move, stuff, seen),
'run' :self.goto(next_move, stuff, seen),
'start' :self.set_bomb(next_move, stuff, seen),
'take' :self.take_item(next_move, stuff, seen),
'tell' :self.talk_to(next_move, stuff, seen),
}
self.obj = {
'armory' :'',
'blaster' :'',
'bomb' :'',
'bridge' :'',
'cabin' :'',
'corridor':'',
'gangway' :'',
'gothon' :'',
'keypad' :'',
'pod' :'',
}
建议?
答案 0 :(得分:2)
您正在保存调用dict中方法的结果。你可能想在__init__()
中想要这样的东西来保存对方法的引用:
self.act = {
'drop' :self.drop_item,
'enter' :self.goto,
'get' :self.take_item,
'go' :self.goto,
'inventory' :self.inventory,
'leave' :self.goto,
'look' :self.show_items,
'run' :self.goto,
'start' :self.set_bomb,
'take' :self.take_item,
'tell' :self.talk_to,
}
即。在不传递参数的情况下引用方法。然后通过执行实际调用来运行该方法以在play()
中执行操作:
self.act["the action"](next_move, stuff, seen)