python用字典实现switch
因为python没有switch语句,一直以来都是用多个if..elif..来实现相同逻辑.
今天看到一个凶残暴力的实现方式,于是动手写写,记下来
from distutils import log def stateA(): log.warn('stateA called') def stateB(): log.warn('stateB called') def stateC(): log.warn('stateC called') def stateDefault(): log.warn('stateDefault called') cases = {'a':stateA, 'b':stateB, 'c':stateC} def switch(case): if case in cases: cases[case]() else: stateDefault() def test(): switch('b') switch('c') switch('a') switch('x') test()
如果每个分支需要处理的逻辑很少,更是可以用lamdba简化,如下:
from distutils import log cases = {'a':lambda:log.warn('in stateA'), 'b':lambda:log.warn('in stateB'), 'c':lambda:log.warn('in stateC')} def switch(case): if case in cases: cases[case]() else: log.warn('in stateDefualt') def test(): switch('b') switch('c') switch('a') switch('x') test()