PythonにおけるSwithch Case文法の実現

7951 ワード

http://blog.csdn.net/suiyunonghen/article/details/3734135
http://blog.csdn.net/longshengguoji/article/details/9918645
他の言語では、switch文は大体こんな感じです。

  
  
  
  
  1. switch (var)
  2. {
  3.     case value1: do_some_stuff1();
  4.     case value2: do_some_stuff2();
  5.     ...
  6.     case valueN: do_some_stuffN();
  7.     default: do_default_stuff();
  8. }
python switch , 3 : A. dictionary values = { value1: do_some_stuff1, value2: do_some_stuff2, ... valueN: do_some_stuffN, } values.get(var, do_default_stuff)() B. lambda result = { 'a': lambda x: x * 5, 'b': lambda x: x + 7, 'c': lambda x: x - 2 }[value](x) C.Brian Beck switch switch
  1. # This class provides the functionality we want. You only need to look at
  2. # this if you want to know how this works. It only needs to be defined
  3. # once, no need to muck around with its internals.
  4. class switch(object):
  5.     def __init__(self, value):
  6.         self.value = value
  7.         self.fall = False
  8.     def __iter__(self):
  9.         """Return the match method once, then stop"""
  10.         yield self.match
  11.         raise StopIteration
  12.     def match(self, *args):
  13.         """Indicate whether or not to enter a case suite"""
  14.         if self.fall or not args:
  15.             return True
  16.         elif self.value in args: # changed for v1.5, see below
  17.             self.fall = True
  18.             return True
  19.         else:
  20.             return False
  21. # The following example is pretty much the exact use-case of a dictionary,
  22. # but is included for its simplicity. Note that you can include statements
  23. # in each suite.
  24. v = 'ten'
  25. for case in switch(v):
  26.     if case('one'):
  27.         print 1
  28.         break
  29.     if case('two'):
  30.         print 2
  31.         break
  32.     if case('ten'):
  33.         print 10
  34.         break
  35.     if case('eleven'):
  36.         print 11
  37.         break
  38.     if case(): # default, could also just omit condition or 'if True'
  39.         print "something else!"
  40.         # No need to break here, it'll stop anyway
pythonではswitch文は使われていません。これはpython大道から簡に至る思想を体現しているべきです。pythonでは一般的に辞書を使ってswitchの代わりに実現します。
[python]view plin copy
ヽoo。ツ utf-8  
  • from __future_. import ディヴィジョン  
  •   
  • def jia(x,y):  
  •     print x+y  
  •   
  • def jian(x,y):  
  •     print x-y  
  •   
  • def ching(x,y):  
  •     print x*y  
  •   
  • def chu(x,y):  
  •     print x/y  
  •   
  • operator = '+':jia'-':jian,'*':chng,':chu}  
  •   
  • def f(x,o,y):  
  •     operator.get(o)(x,y)  
  •   
  • f(3,'+',2)   上のコードは辞書で選択機能を実現しました。C++の中で上記の機能を実現するなら、スイッチで実現しますが、pythonの辞書で実現するのがもっと簡単です。