问题描述
我在我的应用程序中使用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楼
当定义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
变量。
您可以这样做:
类AdventureCmd(cmd.Cmd):
全球游戏状态,如果gamestate =='adventure':提示='\\ n您要做什么?\\ n'其他:提示='\\ n您要做什么?\\ n'#这让我们知道我们现在处于“战斗”游戏状态
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
您可能会在代码中考虑其他一些更改。 例如,将gamestate设置为实例变量而不是全局变量可能是一个好主意,如果您有一个字典将gamestate映射到正确的提示,而不是使用if / elif循环链来更改提示,则将有助于扩展性。
注意:我没有测试上面的代码,因此可能存在输入错误或其他错误,但是我认为基本思想是正确的。