Я использую класс cmd класса Python в своем приложении. Я бы хотел определить cmd.prompt() на лету, но не могу найти способ сделать это. Это то, что у меня есть, что, кажется, не работает:Определить или изменить командную строку с переменной в Python
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'
Я просто питон n00b, так что, возможно, что-то делать с изменением суперклассов или что-то в этом роде, я еще не знаю, как это сделать. Можете ли вы, ребята, дать мне совет?
EDIT: Я также попытался:
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?'