Python中没有内置的switch语句,但可以通过多种方式实现类似的功能。以下是一些常见的替代方案:
1: 使用python官方内置的if/else结构
如果你想实现类似switch/case的功能,最直接的方法是使用if/else结构。
def switch(value):
if value == 1:
return "one"
if value == 2:
return "two"
if value == 42:
return "the answer to the question about life, the universe and everything"
raise Exception("No case found!")
测试:
>>> switch(1)
one
>>> switch(2)
two
>>> switch(3)
…
Exception: No case found!
>>> switch(42)
the answer to the question about life the universe and everything
- if/else结构虽然看起来有些冗余,但这是最直接且效率最高的方法。
- 如果没有匹配的值,可以抛出异常或返回默认值。
2: 使用字典映射函数
另一种方法是创建一个字典,将每个值映射到一个函数。
switch = {
1: lambda: 'one',
2: lambda: 'two',
42: lambda: 'the answer of life the universe and everything',
}
然后添加一个函数
def default_case():
raise Exception('No case found!')
你使用字典的get方法获取给定值的函数来检查和运行它。如果value在dictionary中不存在,则运行default_case。
>>> switch.get(1, default_case)()
one
>>> switch.get(2, default_case)()
two
>>> switch.get(3, default_case)()
…
Exception: No case found!
>>> switch.get(42, default_case)()
the answer of life the universe and everything
你还可以添加一些语法糖,让switch看起来更好:
def run_switch(value):
return switch.get(value, default_case)()
>>> run_switch(1)
one
- 使用字典的get方法可以方便地获取对应的函数,并在没有匹配值时调用默认函数。
- 这种方法的优点是代码更加简洁,易于维护。
3: 使用类的反射机制
你可以使用一个类来模拟switch/case结构。下面是使用类的反射机制(使用getattr()函数将字符串解析为实例的绑定方法)来解决“case”部分。
然后这个反射机制方法被别名为__call__方法来重载()操作符。
class SwitchBase:
def switch(self, case):
m = getattr(self, 'case_{}'.format(case), None)
if not m:
return self.default
return m
__call__ = switch
然后为了让它看起来更好,我们继承SwitchBase类(但它可以在一个类中完成),在那里我们将所有的case定义为方法:
class CustomSwitcher(SwitchBase):
def case_1(self):
return 'one'
def case_2(self):
return 'two'
def case_42(self):
return 'the answer of life, the universe and everything!'
def default(self):
raise Exception('Not a case!')
这样我们就可以使用它了:
>>> switch = CustomSwitcher()
>>> print(switch(1))
one
>>> print(switch(2))
two
>>> print(switch(3))
…
Exception: Not a case!
>>> print(switch(42))
the answer of life, the universe and everything!
- 使用getattr方法动态获取方法。
- 通过__call__方法重载()操作符,使类实例可以像函数一样调用。
4: 使用上下文管理器
另一种方法非常易读且优雅,但比if/else结构效率低得多,就是构建一个像下面这样的类,读取并存储用于比较的值,在上下文中将自身暴露为一个可调用对象,如果与存储的值匹配,则返回true:
class Switch:
def __init__(self, value):
self._val = value
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
return False # Allows traceback to occur
def __call__(self, cond, *mconds):
return self._val in (cond,)+mconds
然后定义这些分支几乎和真正的switch/case结构是一样的(为了更容易展示,在下面的函数中暴露出来):
def run_switch(value):
with Switch(value) as case:
if case(1):
return 'one'
if case(2):
return 'two'
if case(3):
return 'the answer to the question about life, the universe and everything'
# default
raise Exception('Not a case!')
所以执行结果是:
>>> run_switch(1)
one
>>> run_switch(2)
two
>>> run_switch(3)
…
Exception: Not a case!
>>> run_switch(42)
the answer to the question about life, the universe and everything
- 使用上下文管理器with语句,使代码看起来更接近switch/case结构。
- 这种方法的优点是代码可读性高,但缺点是效率较低。
- 这种方法可以通过pip安装的switch模块实现。
- 在实际开发中,if/else结构通常是实现类似switch/case功能的首选方法,因为它简单且效率高。
本文暂时没有评论,来添加一个吧(●'◡'●)