python之switch語句,優化多個if語句


  python中並沒有多分支的語句。像c語言中有switch語句,可以避免多個if的使用場合,簡化代碼。

  python若想實現多分支的功能需要自己構建代碼,涉及到裝飾器的知識點。下面舉個例子。

switch_dicts = {}


def deco(data):
    def wrapper(func):
        if data not in switch_dicts.keys():
            switch_dicts[data] = func

        def wrapper1(*args, **kwargs):
            return func(*args, **kwargs)

        return wrapper1

    return wrapper


@deco(1)
def case1(*args, **kwargs):
    print("case1")


@deco(2)
def case1(*args, **kwargs):
    print("case2")


@deco(3)
def case1(*args, **kwargs):
    print("case3")

#裝飾器自動運行時,會自動將1,2,3裝入字典中
print(switch_dicts)
調用字典中key為1所指向的函數
print(switch_dicts[1]())

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM