pythoncase⽤法_PythonSwitchCase三种实现⽅法代码实例Python没有switch语句,只能通过模拟来对应实现:
⽅法⼀:使⽤dictionary
**values = {
value1: do_some_stuff1,
value2: do_some_stuff2,
...
valueN: do_some_stuffN,
}
<(var, do_default_stuff)()
根据需求可以⾃⾏更改参数内容,灵活运⽤
def add(x,y):
print x+y
def minus(x,y):
print x-y
def multiply(x,y):
print x*y
def div(x,y):
print x/y
def fun_case_list(key,arg1,arg2):
operator = {
'+':add,
'-':minus,
'*':multiply,
'/':div
}
if operator.has_key(key):
(key)(arg1,arg2)
else:
return 'No [%s] case in dic'%key #or do other func
if __name__ == "__main__":
fun_case_list('*',3,5)
fun_case_list('l',3,4)
或者你可以⾃⼰造⼀个类来实现:
class switch_case(object):
def case_to_function(self,case,arg1,arg2):
func_name = 'case_func_'+str(case)
try:
method = getattr(self,func_name)
return method(arg1,arg2)
except AttributeError:
return 'No func found in case list,do default action here' def case_func_add(self,arg1,arg2):
temp = arg1 + arg2
return temp
def case_func_minus(self,arg1,arg2):
temp = arg1 - arg2
return temp
def case_func_multiply(self,arg1,arg2):
temp = arg1 * arg2
return temp
def case_func_div(self,arg1,arg2):
temp = arg1 / arg2
return temp
func = 'minus'
case = switch_case()
print case.case_to_function(func,2,5)
#或者是构造属性去送参数,看个⼈喜好
class switch_case(object):
switch case判断字符串
def __init__(self, case, arg1, arg2):
self.case = str(case)
self.arg1 = arg1
self.arg2 = arg2
def case_to_function(self):
func_name = 'case_func_'+str(self.case)
try:
method = getattr(self,func_name)
return method()
except AttributeError:
return 'No func found in case list,do default action here' def case_func_add(self):
temp = self.arg1 + self.arg2
return temp
def case_func_minus(self):
temp = self.arg1 - self.arg2
return temp
def case_func_multiply(self):
temp = self.arg1 * self.arg2
return temp
def case_func_div(self):
temp = self.arg1 / self.arg2
return temp
func = 'minxus'
case = switch_case(func,2,5)
print case.case_to_function()
⽅法⼆:使⽤lambda
result = {
'a': lambda x: x * 5,
'b': lambda x: x + 7,
'c': lambda x: x - 2
}[value](x)
⽅法三:Brian Beck提供了⼀个类 switch 来实现switch的功能class switch(object):
def __init__(self, value):
self.value = value
self.fall = False
def __iter__(self):
"""Return the match method once, then stop"""
yield self.match
raise StopIteration
def match(self, *args):
"""Indicate whether or not to enter a case suite"""
if self.fall or not args:
return True
elif self.value in args: # changed for v1.5, see below
self.fall = True
return True
else:
return False
v = 'two'
for case in switch(v):
if case('one'):
print 1
break
if case('two'):
print 2
break
if case('ten'):
print 10
break
if case('eleven'):
print 11
break
if case(): # default, could also just omit condition or 'if True'
print "something else!"
# No need to break here, it'll stop anyway
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持脚本之家。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。