Python switch/case语句实现方法

与Java、C\C++等语言不同,Python中是不提供switch/case语句的,这一点让我感觉到很奇怪。我们可以通过如下几种方法来实现switch/case语句。

使用if…elif…elif…else 实现switch/case

可以使用if…elif…elif..else序列来代替switch/case语句,这是大家最容易想到的办法。但是随着分支的增多和修改的频繁,这种代替方式并不很好调试和维护。

使用字典 实现switch/case

可以使用字典实现switch/case这种方式易维护,同时也能够减少代码量。如下是使用字典模拟的switch/case实现:


def num_to_string(num):
    numbers = {
        0 : "zero",
        1 : "one",
        2 : "two",
        3 : "three"
    }

    return numbers.get(num, None)

if __name__ == "__main__":
    print num_to_string(2)
    print num_to_string(5)

执行结果如下:

two
None

Python字典中还可以包括函数或Lambda表达式,代码如下:

def success(msg):
    print msg

def debug(msg):
    print msg

def error(msg):
    print msg

def warning(msg):
    print msg

def other(msg):
    print msg

def notify_result(num, msg):
    numbers = {
        0 : success,
        1 : debug,
        2 : warning,
        3 : error
    }

    method = numbers.get(num, other)
    if method:
        method(msg)

if __name__ == "__main__":
    notify_result(0, "success")
    notify_result(1, "debug")
    notify_result(2, "warning")
    notify_result(3, "error")
    notify_result(4, "other")

执行结果如下:

success
debug
warning
error
other

通过如上示例可以证明能够通过Python字典来完全实现switch/case语句,而且足够灵活。尤其在运行时可以很方便的在字典中添加或删除一个switch/case选项。

在类中可使用调度方法实现switch/case

如果在一个类中,不确定要使用哪种方法,可以用一个调度方法在运行的时候来确定。代码如下:

class switch_case(object):

    def case_to_function(self, case):
        fun_name = "case_fun_" + str(case)
        method = getattr(self, fun_name, self.case_fun_other)
        return method

    def case_fun_1(self, msg):
        print msg

    def case_fun_2(self, msg):
        print msg

    def case_fun_other(self, msg):
        print msg


if __name__ == "__main__":
    cls = switch_case()
    cls.case_to_function(1)("case_fun_1")
    cls.case_to_function(2)("case_fun_2")
    cls.case_to_function(3)("case_fun_other")

执行结果如下:

case_fun_1
case_fun_2
case_fun_other

总结

就个人来说,使用字典来实现switch/case是最为灵活的,但是理解上也有一定的难度。

  • 52
    点赞
  • 169
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
Python中没有内置的switch/case语句。与Java、C/C++等语言不同,Python中没有直接提供switch/case语句的功能。但是,我们可以通过几种方法实现类似功能的结构。 第一种方法是使用if...elif...elif...else语句实现类似switch/case的功能。将需要判断的条件依次放在if和elif语句中,根据条件执行相应的代码块。最后,可以使用else语句来处理默认情况。虽然这种方法比较简单,但是当分支较多或需要频繁修改时可能不够方便和易于维护。 第二种方法是使用字典来实现类似switch/case的功能。可以将不同的条件作为字典的键,对应的代码块作为字典的值。然后,可以通过检索字典来执行相应的代码块。这种方法非常灵活,可以在运行时方便地添加或删除switch/case选项。 第三种方法是在类中使用调度方法实现类似switch/case的功能。可以将不同的条件作为方法的参数,根据不同的条件执行相应的方法体。这种方法适用于需要在类中多次使用相同的条件判断。 综上所述,尽管Python中没有直接提供switch/case语句,但可以使用if...elif...elif...else语句、字典或调度方法实现类似的功能。具体选择哪种方法取决于你的需求和代码结构。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [Python switch/case语句实现方法](https://blog.csdn.net/l460133921/article/details/74892476)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值