switch语句被认为是有害的。这可能就是Python没有它的原因。fallthrough行为是C代码中错误的主要来源。很容易忘记break;,这就是为什么C不允许它,你必须使用显式的goto。在Python的dict of functions方法中也是如此。您调用了下一个函数。”显性胜于隐性”。在
对函数(带标识符键)进行dict的最简单方法是使用class声明。在class switch:
def a():
print('a')
switch.b()
def b():
print('b')
switch.c()
def c():
print('c')
def d():
switch.e()
def e():
print('de')
def f():
switch.g()
def g():
print('fg')
def h():
print('h')
def i():
print('i')
switch.default()
def default():
print('foo')
像这样使用它。在
^{pr2}$
如果需要实际的dict,还可以提取__dict__attr>>> switch.__dict__.get('e', 'default')()
de
您可以使用if语句进行类似的显式处理。在def switch(case)
if case == a:
doA()
case = b
if case == b:
doB()
case = c
if case == c:
doC()
return
if case == d:
case = e
if case == e:
doDE()
return
if case == f:
case = g
if case == g:
doFG()
case = h
if case == h:
doH()
return
if case == i:
doI()
foo()
如果您担心改变条件的副作用,或者如果条件比简单的等式更复杂,并且不想重复它们,可以使用helper变量,而不是重新分配case。在def switch(case):
fall = False
if case == a:
doA()
fall = True
if fall or case == b:
doB()
fall = True
if fall or case == c:
doC()
return
if case == d:
fall = True
if fall or case == e:
doDE()
return
if case == f:
fall = True
if fall or case == g:
doFG()
fall = True
if fall or case == h:
doH()
return
if case == i:
doI()
foo()