python中中Switch/Case实现的示例代码实现的示例代码
本篇文章主要介绍了python中Switch/Case实现的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做
个参考。一起跟随小编过来看看吧
学习Python过程中,发现没有switch-case,过去写C习惯用Switch/Case语句,官方文档说通过if-elif实现。所以不妨自己来实现
Switch/Case功能。
使用if…elif…elif…else 实现switch/case
可以使用if…elif…elif..else序列来代替switch/case语句,这是大家最容易想到的办法。但是随着分支的增多和修改的频繁,这
种代替方式并不很好调试和维护。
方法一方法一
通过字典实现
def foo(var):
return {
'a': 1,
'b': 2,
'c': 3,
}.get(var,'error') #'error'为默认返回值,可自设置
方法二方法二
通过匿名函数实现
def foo(var,x):
return {
'a': lambda x: x+1,
'b': lambda x: x+2,
'c': lambda x: x+3,
}[var](x)
方法三方法三
通过定义类实现
参考Brian Beck通过类来实现Swich-case
# This class provides the functionality we want. You only need to look at
# this if you want to know how this works. It only needs to be defined
# once, no need to muck around with its internals.
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
# The following example is pretty much the exact use-case of a dictionary,
# but is included for its simplicity. Note that you can include statements
# in each suite.
v = 'ten'
for case in switch(v):
if case('one'):
print 1
break
if case('two'):
print 2
break
if case('ten'):
评论0
最新资源