2015-08-08 63 views
3

我正在尝试做一些命令切换。比If Ifse更智能

if 'Who' in line.split()[:3]: 
    Who(line) 
elif 'Where' in line.split()[:3]: 
    Where(line) 
elif 'What' in line.split()[:3]: 
    What(line) 
elif 'When' in line.split()[:3]: 
    When(line) 
elif 'How' in line.split()[:3]: 
    How(line) 
elif "Make" in line.split()[:3]: 
    Make(line) 
elif "Can You" in line.split()[:3]: 
    CY(line) 
else: 
    print("OK") 

所以说明。如果Who,What等位于命令的前3个字中,则执行相应的功能。我只想知道是否有一个更明智的方法来做到这一点,而不是很多ifelifelse

+0

'case'或'switch',无论哪个在python中支持 –

+0

使用'dictionary'。 –

+3

@TheBrofessor:呃,都不支持。 – DSM

回答

9

尝试使用键作为命令名称和实际命令功能的值来创建字典。例如:

def who(): 
    ... 

def where(): 
    ... 

def default_command(): 
    ... 

commands = { 
    'who': who, 
    'where': where, 
    ... 
} 

# usage 
cmd_name = line.split()[:3][0] # or use all commands in the list 
command_function = commands.get(cmd_name, default_command) 
command_function() # execute command 
+5

你的'cmd_name'是一个字符串列表,所以我们不能用它来索引字典。 – DSM

+0

这是完美的。除了@DSM说的这个工作。我搜索了一些与此类似的东西,但我无法围绕应用它,谢谢你的帮助 – user1985351

+0

啊,我明白了,我会纠正它。谢谢! – plamut

3

这里是一个不同的方法:从所述cmd库模块使用命令调度:

import cmd 

class CommandDispatch(cmd.Cmd): 
    prompt = '> ' 

    def do_who(self, arguments): 
     """ 
     This is the help text for who 
     """ 
     print 'who is called with argument "{}"'.format(arguments) 

    def do_quit(self, s): 
     """ Quit the command loop """ 
     return True 

if __name__ == '__main__': 
    cmd = CommandDispatch() 
    cmd.cmdloop('Type help for a list of valid commands') 
    print('Bye') 

上述程序将启动命令循环与提示'> '。它提供3个命令:help(由cmd.Cmd提供),whoquit。下面是一个简单的互动:

$ python command_dispatch.py 
Type help for a list of valid commands 
> help 

Documented commands (type help <topic>): 
======================================== 
help quit who 

> help who 

     This is the help text for who 

> who am I? 
who is called with argument "am I?" 
> who 
who is called with argument "" 
> quit 
Bye 

注:

  • 您的命令也将作为帮助文本
  • cmd.Cmd需要的所有调度细节,以便您可以集中精力实施护理文档字符串您的命令
  • 如果要提供名为why的命令,请创建一个名为do_why的方法,并且该命令将可用。
  • 请参阅文档以获取更多信息。
+0

好吧,这回答几乎所有的问题。谢谢! – user1985351