python的模拟switch方案

def case1():                            # 第一种情况执行的函数
    print('This is the case1')

def case2():                            # 第二种情况执行的函数
    print('This is the case2')

def case3():                            # 第三种情况执行的函数
    print('This is the case3')

def default():                          # 默认情况下执行的函数
    print('No such case')

switch = {'case1': case1,                # 注意此处不要加括号
          'case2': case2,                # 注意此处不要加括号
          'case3': case3,                # 注意此处不要加括号
          }

choice = 'case1'                         # 获取选择
switch.get(choice, default)()            # 执行对应的函数,如果没有就执行默认的函数

发表回复

您的电子邮箱地址不会被公开。