python switch...case语句实现代码

发布时间:2019-10-16编辑:脚本学堂
在python中没有switch case分支选择语句,那就自己来实现一个类似switch case语句的功能吧,这样就可以减少使用if else语句了。

参考链接:
http://code.activestate.com/recipes/410692/

代码:
 

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 = 'ten'
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(): # 默认
        print "something else!"