Python 类似switch/case语句实现方法 获取文件内容匹配函数并执行

这个主要提供了一种思路,这个不太好理解,我彻底敲了一遍,心里有点低。参考下面的文章
标题:Python switch/case语句实现方法
来源:https://blog.csdn.net/l460133921/article/details/74892476

与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实现:

#!/usr/bin/python
# -*- coding: utf-8 -*-

def zkper(msg):
    print msg
    print ("zkper函数")

def scp(msg):
    print msg
    print ("scp函数")

def cou(msg):
    print msg
    print ("cou函数")

def error(msg):
    print msg   
    print ("error函数")

def other(msg):
    print msg
    print (msg+"不更新")

def notify_result(num, msg):
    numbers = {
        'zkper=1' : zkper,
        'scp=1' : scp,
        'cou=1' : cou,
        3 : error
    }

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

def update_all_aw():
    for line in open("upmips.cfg"):
        a=line.strip()
#       print(a)
        if __name__ == "__main__":
            notify_result(a, a) 
        print ("===")   

update_all_aw()

umpips.cfg的内容为

zkper=1
scp=1
cou=0
bjs=0

设计思路,=1的更新该函数,=0表示不更新。
里面使用了逐行读取配合字典函数来达到效果。

猜你喜欢

转载自blog.51cto.com/weiruoyu/2304158