python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python Switch Case

Python Switch Case三种实现方法代码实例

作者:萧蔷ink

这篇文章主要介绍了Python Switch Case2种实现方法代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

Python没有switch语句,只能通过模拟来对应实现:

方法一:使用dictionary

**values = {
value1: do_some_stuff1,
value2: do_some_stuff2,
...
valueN: do_some_stuffN,
}
values.get(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):
    return operator.get(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):
  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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文