Python 词典替换 switch/case 中的失败
Fall-through in Python dictionary replacement of switch/case
我尝试在 Python 中实现 switch/case 机制。在阅读了几个网站和此处的问题后(例如 this one), I built the code below. But it behaves wrong, having what I understand to be - a fall-through, which can be even problematic to get,肯定不是默认的预期结果。
def something():
print 'something'
def somethingElse():
print 'something else'
def switch():
cases = {
0: something(),
1: something(),
2: something(),
3: something(),
4: something(),
5: something()
}
cases.get(2, somethingElse())
switch()
(显然每个案例的相同开关只是为了示例)
当我 运行 它时,我希望 something()
只 运行 一次(因为我手动输入 2
)。但是,控制台中的输出是:
something
something
something
something
something
something
something else
什么意思是运行6倍加上默认值运行。我不明白这段代码中的什么允许这样的失败?或者问题可能不同?
这里是 Python 2.7.12。
您的词典在创建案例时会调用每个函数。您的函数打印(副作用)而不是 return 字符串,因此您会看到所有打印到控制台的字符串。
相反,您的开关应该 return 一个函数,然后您可以调用该函数。
def something():
print 'something'
def somethingElse():
print 'something else'
def switch():
cases = {
0: something,
1: something,
2: something,
3: something,
4: something,
5: something
}
# All of the values in `cases` are functions so it is safe
# to call whatever `cases.get(...)` returns.
cases.get(2, somethingElse)()
switch()
你需要return函数名然后调用它。像这样
def something():
print ('something')
def somethingElse():
print ('something else')
cases = {1: something, 2: something, 3:something, 4:something,5:something}
result = cases.get(2, somethingElse)()
~
我尝试在 Python 中实现 switch/case 机制。在阅读了几个网站和此处的问题后(例如 this one), I built the code below. But it behaves wrong, having what I understand to be - a fall-through, which can be even problematic to get,肯定不是默认的预期结果。
def something():
print 'something'
def somethingElse():
print 'something else'
def switch():
cases = {
0: something(),
1: something(),
2: something(),
3: something(),
4: something(),
5: something()
}
cases.get(2, somethingElse())
switch()
(显然每个案例的相同开关只是为了示例)
当我 运行 它时,我希望 something()
只 运行 一次(因为我手动输入 2
)。但是,控制台中的输出是:
something
something
something
something
something
something
something else
什么意思是运行6倍加上默认值运行。我不明白这段代码中的什么允许这样的失败?或者问题可能不同?
这里是 Python 2.7.12。
您的词典在创建案例时会调用每个函数。您的函数打印(副作用)而不是 return 字符串,因此您会看到所有打印到控制台的字符串。
相反,您的开关应该 return 一个函数,然后您可以调用该函数。
def something():
print 'something'
def somethingElse():
print 'something else'
def switch():
cases = {
0: something,
1: something,
2: something,
3: something,
4: something,
5: something
}
# All of the values in `cases` are functions so it is safe
# to call whatever `cases.get(...)` returns.
cases.get(2, somethingElse)()
switch()
你需要return函数名然后调用它。像这样
def something():
print ('something')
def somethingElse():
print ('something else')
cases = {1: something, 2: something, 3:something, 4:something,5:something}
result = cases.get(2, somethingElse)()
~