Python Switch Case三种实现方法代码实例
Python没有switch语句,只能通过模拟来对应实现:
方法一:使用dictionary
**values={
value1:do_some_stuff1,
value2:do_some_stuff2,
...
valueN:do_some_stuffN,
}
values.get(var,do_default_stuff)()
根据需求可以自行更改参数内容,灵活运用
defadd(x,y): printx+y defminus(x,y): printx-y defmultiply(x,y): printx*y defdiv(x,y): printx/y deffun_case_list(key,arg1,arg2): operator={ '+':add, '-':minus, '*':multiply, '/':div } ifoperator.has_key(key): returnoperator.get(key)(arg1,arg2) else: return'No[%s]caseindic'%key#ordootherfunc if__name__=="__main__": fun_case_list('*',3,5) fun_case_list('l',3,4)
或者你可以自己造一个类来实现:
classswitch_case(object): defcase_to_function(self,case,arg1,arg2): func_name='case_func_'+str(case) try: method=getattr(self,func_name) returnmethod(arg1,arg2) exceptAttributeError: return'Nofuncfoundincaselist,dodefaultactionhere' defcase_func_add(self,arg1,arg2): temp=arg1+arg2 returntemp defcase_func_minus(self,arg1,arg2): temp=arg1-arg2 returntemp defcase_func_multiply(self,arg1,arg2): temp=arg1*arg2 returntemp defcase_func_div(self,arg1,arg2): temp=arg1/arg2 returntemp func='minus' case=switch_case() printcase.case_to_function(func,2,5) #或者是构造属性去送参数,看个人喜好 classswitch_case(object): def__init__(self,case,arg1,arg2): self.case=str(case) self.arg1=arg1 self.arg2=arg2 defcase_to_function(self): func_name='case_func_'+str(self.case) try: method=getattr(self,func_name) returnmethod() exceptAttributeError: return'Nofuncfoundincaselist,dodefaultactionhere' defcase_func_add(self): temp=self.arg1+self.arg2 returntemp defcase_func_minus(self): temp=self.arg1-self.arg2 returntemp defcase_func_multiply(self): temp=self.arg1*self.arg2 returntemp defcase_func_div(self): temp=self.arg1/self.arg2 returntemp func='minxus' case=switch_case(func,2,5) printcase.case_to_function()
方法二:使用lambda
result={
'a':lambdax:x*5,
'b':lambdax:x+7,
'c':lambdax:x-2
}[value](x)
方法三:BrianBeck提供了一个类switch来实现switch的功能
classswitch(object): def__init__(self,value): self.value=value self.fall=False def__iter__(self): """Returnthematchmethodonce,thenstop""" yieldself.match raiseStopIteration defmatch(self,*args): """Indicatewhetherornottoenteracasesuite""" ifself.fallornotargs: returnTrue elifself.valueinargs:#changedforv1.5,seebelow self.fall=True returnTrue else: returnFalse v='two' forcaseinswitch(v): ifcase('one'): print1 break ifcase('two'): print2 break ifcase('ten'): print10 break ifcase('eleven'): print11 break ifcase():#default,couldalsojustomitconditionor'ifTrue' print"somethingelse!" #Noneedtobreakhere,it'llstopanyway
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。