寫了一陣子python腳本了,今天寫個小功能時用了n多if...else,看着真讓人厭煩,然后就想看看python的switch...case怎么用,在網上找了半天,才知道python是沒有自帶switch...case語句的,還好找到一個不錯的例子,在此記錄,以備后用。代碼來自:http://code.activestate.com/recipes/410692/
1 #!/bin/env python 2 #coding=utf-8 3 4 # This class provides the functionality we want. You only need to look at 5 # this if you want to know how this works. It only needs to be defined 6 # once, no need to muck around with its internals. 7 class switch(object): 8 def __init__(self, value): 9 self.value = value 10 self.fall = False 11 12 def __iter__(self): 13 """Return the match method once, then stop""" 14 yield self.match 15 raise StopIteration 16 17 def match(self, *args): 18 """Indicate whether or not to enter a case suite""" 19 if self.fall or not args: 20 return True 21 elif self.value in args: # changed for v1.5, see below 22 self.fall = True 23 return True 24 else: 25 return False 26 27 28 # The following example is pretty much the exact use-case of a dictionary, 29 # but is included for its simplicity. Note that you can include statements 30 # in each suite. 31 v = 'ten' 32 for case in switch(v): 33 if case('one'): 34 print 1 35 break 36 if case('two'): 37 print 2 38 break 39 if case('ten'): 40 print 10 41 break 42 if case('eleven'): 43 print 11 44 break 45 if case(): # default, could also just omit condition or 'if True' 46 print "something else!" 47 # No need to break here, it'll stop anyway 48 49 # break is used here to look as much like the real thing as possible, but 50 # elif is generally just as good and more concise. 51 52 # Empty suites are considered syntax errors, so intentional fall-throughs 53 # should contain 'pass' 54 c = 'z' 55 for case in switch(c): 56 if case('a'): pass # only necessary if the rest of the suite is empty 57 if case('b'): pass 58 # ... 59 if case('y'): pass 60 if case('z'): 61 print "c is lowercase!" 62 break 63 if case('A'): pass 64 # ... 65 if case('Z'): 66 print "c is uppercase!" 67 break 68 if case(): # default 69 print "I dunno what c was!" 70 71 # As suggested by Pierre Quentel, you can even expand upon the 72 # functionality of the classic 'case' statement by matching multiple 73 # cases in a single shot. This greatly benefits operations such as the 74 # uppercase/lowercase example above: 75 import string 76 c = 'A' 77 for case in switch(c): 78 if case(*string.lowercase): # note the * for unpacking as arguments 79 print "c is lowercase!" 80 break 81 if case(*string.uppercase): 82 print "c is uppercase!" 83 break 84 if case('!', '?', '.'): # normal argument passing style also applies 85 print "c is a sentence terminator!" 86 break 87 if case(): # default 88 print "I dunno what c was!" 89 90 # Since Pierre's suggestion is backward-compatible with the original recipe, 91 # I have made the necessary modification to allow for the above usage.