Python中的函数字典
起因是在git上库的时候遇到一个huge_method问题,但重复代码并不多。
想到C语言中的函数指针表驱动方法,对比到python,使用函数字典抽取函数,解决大函数问题。
并且可以灵活配置函数用来选择性画图,非常方便。
import re
def add(x, y):
return x + y
def sub(x, y):
return x - y
def mul(x, y):
return x * y
def div(x, y):
return x / y
def main():
inStr = "2+3"
inList = re.split("(\W+)", inStr)
inList[1] = inList[1].strip()
print(inList)
# Method 1:
if inList[1] == "+":
print(add(int(inList[0]), int(inList[2])))
elif inList[1] == "-":
print(sub(int(inList[0]), int(inList[2])))
elif inList[1] == "*":
print(mul(int(inList[0]), int(inList[2])))
elif inList[1] == "/":
print(div(int(inList[0]), int(inList[2])))
else:
pass
# Method 2:
try:
operator = {"+": add, "-": sub, "*": mul, "/": div}
print(operator[inList[1]](int(inList[0]), int(inList[2])))
except KeyError:
pass
if __name__ == '__main__':
main()
原示例的博客来源:
https://www.cnblogs.com/lxw0109/p/python-funcname-dictvalue.html