我正在尝试(某种程度上)切换命令。
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等位于命令的前三个字中,则执行相应的函数。我只想知道是否有比很多if,elif和else更聪明的方法来做这件事
发布于 2015-08-08 17:14:53
尝试创建一个字典,其中键是命令名,值是实际的命令函数。示例:
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发布于 2015-08-08 17:34:04
下面是一种不同的方法:使用来自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提供)、who和quit。下面是一个示例交互:
$ 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的方法,该命令将可用。https://stackoverflow.com/questions/31896495
复制相似问题