比If Else更聪明

时间:2015-08-08 17:09:36

标签: python if-statement

我正在尝试切换(各种)命令。

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")

所以解释。如果WhoWhat等位于命令的前3个单词中,则执行相应的函数。我只是想知道除了很多ifelifelse之外还有更聪明的方法吗?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

注意:

  • 您的命令的docstring也将作为帮助文本
  • cmd.Cmd负责处理所有调度细节,以便您专注于实施命令
  • 如果要提供名为why的命令,请创建名为do_why的方法,该命令将可用。
  • 有关详细信息,请参阅文档。