看了不少帖子,几乎都是采用字典的.get()方法实现,据说有个弊端:“会将字典每个带括号的方法都执行一遍”。
如博文 python小技巧--用字典映射代替switch case语句 的内容和评论。
以下方法可避免该弊端,并可以传参。如有不足请指正!
#!/usr/bin/python3
# conf_cmd = conf_items["cmd"].split(":")[0]
test_no = "T1"
#test_no = "T2"
#test_no = "T3"
id = 1
def test1(id):
print("test1:%d" % id)
def test2(id):
print("test2")
def test3(id):
print("test3")
funcs = {"T1": test1,
"T2": test2,
"T3": test3}
try:
func = funcs[test_no]
func(id)
except Exception:
pass
输出:
test1:1