我已经学习了许多例子,说明如何用Python创建字典,而不是用开关-case语句,但出于某种原因,我的代码似乎不起作用。函数ViewCommands,当输入"viewCommands“(作为命令)时,它应该像在脚本开始时那样执行,而不是被执行。

ViewCommands()
while True:
print()
print('?>> What command would you like to execute?:')
command = input()
print('>>> Executing command: ', command)
switcher = {
'viewCommands': ViewCommands,
'terminate': Terminate,
'viewSentences': ViewSentences,
'addSentences': AddSentences
}
case = switcher.get(command, '!');
if case == '!': print('!>> INVALID INPUT - NOT AN OPTION')当我在每个引用中添加括号时.就像这样:

ViewCommands()
while True:
print()
print('?>> What command would you like to execute?:')
command = input()
print('>>> Executing command: ', command)
switcher = {
'viewCommands': ViewCommands(),
'terminate': Terminate(),
'viewSentences': ViewSentences(),
'addSentences': AddSentences()
}
case = switcher.get(command, '!');
if case == '!': print('!>> INVALID INPUT - NOT AN OPTION')...it确实按预期进行了调用,但随后我遇到了一个错误,它意外地被调用,尽管它在字典查询中不应该被引用。
有人知道我为什么会遇到这个问题吗?任何建议都将不胜感激,并感谢提前!
发布于 2021-05-16 00:49:41
在关闭python函数调用上的括号)的确切时刻,它将被执行,不管它在哪里。这就是在第二个代码块中发生的事情: Terminate()正在执行,但是您不希望在那里执行它。您在上面一节中的代码就是要走的路。在case变量签名之后,可以执行在末尾添加括号的函数。
while True:
print()
print('?>> What command would you like to execute?:')
command = input()
print('>>> Executing command: ', command)
switcher = {
'viewCommands': ViewCommands,
'terminate': Terminate,
'viewSentences': ViewSentences,
'addSentences': AddSentences
}
case = switcher.get(command, '!');
if case == '!':
print('!>> INVALID INPUT - NOT AN OPTION')
else:
case()PS:我无法检查代码,因为您没有提供ViewCommands、Terminate、ViewSentences和AddSentences做什么,也没有提供它们接收的参数。
发布于 2021-05-16 01:06:53
这是一种缩短和避免不必要的if语句的方法。Lambda函数确实很漂亮,不是吗?
我在它之后添加了一个(),因为字典case语句得到的是函数对象,它由后面的()执行,与lambda函数相同。
ViewCommands()
while True:
print()
print('?>> What command would you like to execute?:')
command = input()
print('>>> Executing command: ', command)
switcher = {
'viewCommands': ViewCommands,
'terminate': Terminate,
'viewSentences': ViewSentences,
'addSentences': AddSentences
}
case = switcher.get(command, lambda: print('!>> INVALID INPUT - NOT AN OPTION'))()发布于 2021-08-19 04:14:03
在Python 3.10提供了match/case语句之前,您可以定义一个开关函数,它可以使代码更易于接受和更易于维护:
开关功能如下:
def switch(v): yield lambda *c: v in c你可以和if/elif/else一起使用它..。
for case in switch(command):
if case('viewCommands') : ViewCommands()
elif case('terminate') : Terminate()
elif case('viewSentences'): ViewSentences()
elif case('addSentences') : AddSentences()
else: print("bad command")或者以更像C的方式.
for case in switch(command):
if case('viewCommands') : ViewCommands() ; break
if case('terminate') : Terminate() ; break
if case('viewSentences'): ViewSentences() ; break
if case('addSentences') : AddSentences() ; break
else: print("bad command")https://stackoverflow.com/questions/67552263
复制相似问题