在Python中使用变量定义或更改命令提示符

时间:2015-10-25 15:05:12

标签: python

我在我的应用中使用Python的cmd类。我希望能够动态定义cmd.prompt(),但无法找到方法。这就是我所拥有的,这似乎不起作用:

gamestate = 'adventure' #gamestate is either 'adventure' or 'battle'

def changestate(arg):
    global gamestate
    print('Right now the gamestate is {}'.format(gamestate))
    if not arg == '':
        print("Now we are changing the gamestate from {} to {}".format(gamestate, arg.lower()))
        gamestate = arg.lower()
        print('We have changed the gamestate to {}'.format(gamestate))
    else:
        print('{} isn\'t a valid gamestate'.format(arg.upper()))

class AdventureCmd(cmd.Cmd):    
    global gamestate
    if gamestate == 'adventure':
        prompt = '\nWhat do you do?\n'
    else:
        prompt = '\nWhat do you battle?\n' #this lets us know we are now in 'battle' gamestate  

    def do_changestate(self,arg):
        changestate(arg) #'changestate battle' changes the gamestate to 'battle'

if __name__ == '__main__':
    AdventureCmd().cmdloop()

这是我得到的输出:

What do you do?
changestate adventure
Right now the gamestate is adventure
Now we are changing the gamestate from adventure to adventure
We have changed the gamestate to adventure

What do you do?
changestate battle
Right now the gamestate is adventure
Now we are changing the gamestate from adventure to battle
We have changed the gamestate to battle

What do you do? #should be 'What do you battle'

我只是一个python n00b,所以它可能与修改超类或类似我不知道该怎么做的事情有关。你能给我一些建议吗?

编辑:我也试过了:

class AdventureCmd(cmd.Cmd):
    global gamestate
    def preloop(self):
        if gamestate == 'adventure':
            self.prompt = '\nWhat do you do?'
        elif gamestate == 'battle':
            self.prompt = '\nWhat do you battle?'

1 个答案:

答案 0 :(得分:0)

在定义AdventureCmd类时,大多数代码只运行一次。每次用户提供输入时都不会运行它。具体来说,此代码仅在定义类时运行一次:

global gamestate
if gamestate == 'adventure':
    prompt = '\nWhat do you do?\n'
else:
    prompt = '\nWhat do you battle?\n' #this lets us know we are now in 'battle' gamestate

因此,您永远不会重新定义prompt变量。你可以这样做:

class AdventureCmd(cmd.Cmd):
    全球游戏状态     如果gamestate =='冒险':         提示=' \ n你做什么?\ n'     其他:         提示=' \ n你在战斗什么?\ n' #this让我们知道我们现在正在进行战斗'游戏状态

def do_changestate(self,arg):
    changestate(arg)
    # Note we're setting self.prompt here as the prompt is an
    # instance variable for this instance of AdventureCmd. Note also
    # that we change the prompt in the method that gets called to
    # handle the command
    if gamestate == 'adventure':
        prompt = '\nWhat do you do?\n'
    else:
        prompt = '\nWhat do you battle?\n' #this lets us know we are now in 'battle' gamestate  

您可能会在代码中考虑其他一些更改。例如,将游戏状态变为实例变量而不是全局变量可能是一个好主意,如果不是使用if / elif循环链来改变提示,而是将游戏状态映射到游戏状态,它将有助于扩展性。正确的提示。

注意:我没有测试上面的代码,所以可能存在拼写错误或其他错误,但我认为基本想法是正确的。