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]())