当前位置: 移动技术网 > IT编程>软件设计>设计模式 > 字符串变为函数

字符串变为函数

2020年07月16日  | 移动技术网IT编程  | 我要评论

    今天看到一段代码,在一字典中有个字段为gt,gte,lt,lte,然后根据此字段进行判断,例子代码如下:

dict_test1 = {"A":2,"B": 3, "rule":"gt"}
dict_test2 = {"A":2,"B": 3, "rule":"gte"}
dict_test3 = {"A":2,"B": 3, "rule":"lt"}
# 需要对最后的rule进行判断,然后判断前面A,B谁更大,然后进行其他流程操作
if dict_test1['rule'] == "gt":
    if A > B :
        control(1)
    else:
        control(2)
elif dict_test1['rule'] == "gte":
    if A >= B :
        control(1)
    else:
        control(2)
elif dict_test1['rule'] == "lte":
    if A <= B :
        control(1)
    else:
        control(1)
elif dict_test1['rule'] == "lt":
    if A < B :
        control(1)
    else:
        control(2)

看到这样的代码,感觉太麻烦了,特别是如果第二层判断后,如果代码重复,那完全就是消耗性能,以及冗余的代码。

优化后:

from operator import lt, gt, ge, le

dict_test1 = {"A":2,"B": 3, "rule":"gt"}
dict_test2 = {"A":2,"B": 3, "rule":"ge"}
dict_test3 = {"A":2,"B": 3, "rule":"lt"}
dict_test4 = {"A":2,"B": 3, "rule":"le"}
if locals()[dict_test1["rule"]](A,B):
    print("A", dict_test1["rule"], "B")
    pass
else:
    pass

主要优化:1 将rule中的gte,lte需要改为le(小于等于),ge(大于等于)
                   2 多个步骤优化成一个,自动进行判断。无需其他
注意点:

  1. 需要提前将相关函数import进来
  2. 转化方式:locals()[func](**arg)
  3. 通过globals 也是可以的,看个人需求,方式和locals一样


 

本文地址:https://blog.csdn.net/junxieshiguan/article/details/107353565

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网