pythonca⽤法_PythonSwitchCa三种实现⽅法代码实例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_ca_list(key,arg1,arg2):
operator = {
'+':add,
'-':minus,
va
'*':multiply,
'/':div
}
if operator.has_key(key):
(key)(arg1,arg2)
el:
return 'No [%s] ca in dic'%key #or do other func
if __name__ == "__main__":
fun_ca_list('*',3,5)
fun_ca_list('l',3,4)
或者你可以⾃⼰造⼀个类来实现:
class switch_ca(object):
def ca_to_function(lf,ca,arg1,arg2):
func_name = 'ca_func_'+str(ca)
try:
method = getattr(lf,func_name)
return method(arg1,arg2)
except AttributeError:
圣诞歌曲下载return 'No func found in ca list,do default action here' def ca_func_add(lf,arg1,arg2):
temp = arg1 + arg2
return temp
def ca_func_minus(lf,arg1,arg2):
temp = arg1 - arg2
return temp
def ca_func_multiply(lf,arg1,arg2):
temp = arg1 * arg2
return temp
def ca_func_div(lf,arg1,arg2):行长英文>专四作文模板
temp = arg1 / arg2
return temp
func = 'minus'writer
ca = switch_ca()
print ca.ca_to_function(func,2,5)
#或者是构造属性去送参数,看个⼈喜好
烛之武退秦师翻译class switch_ca(object):
def __init__(lf, ca, arg1, arg2):
lf.ca = str(ca)
lf.arg1 = arg1
lf.arg2 = arg2
def ca_to_function(lf):
func_name = 'ca_func_'+str(lf.ca)
try:
method = getattr(lf,func_name)
return method()
except AttributeError:
return 'No func found in ca list,do default action here' def ca_func_add(lf):
temp = lf.arg1 + lf.arg2
return temp
def ca_func_minus(lf):
temp = lf.arg1 - lf.arg2
return temp
def ca_func_multiply(lf):
temp = lf.arg1 * lf.arg2
return temp
def ca_func_div(lf):
temp = lf.arg1 / lf.arg2
return temp
func = 'minxus'thegift
ca = switch_ca(func,2,5)
print ca.ca_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__(lf, value):
lf.value = value
漫语lf.fall = Fal
def __iter__(lf):
"""Return the match method once, then stop"""
yield lf.match
rai StopIteration
def match(lf, *args):
"""Indicate whether or not to enter a ca suite"""
if lf.fall or not args:
return True
elif lf.value in args: # changed for v1.5, e below
lf.fall = True
return True
el:
return Fal
v = 'two'
for ca in switch(v):
homework是什么意思if ca('one'):
print 1
break
if ca('two'):
print 2
break
if ca('ten'):
print 10
break
if ca('eleven'):
print 11
break
if ca(): # default, could also just omit condition or 'if True'
print "something el!"
# No need to break here, it'll stop anyway
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持脚本之家。