python中怎么实现代码重构

python中怎么实现代码重构,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

重构前

import redef count(s):while '/' in s:result = re.findall('([-]?\d+\.\d+|[-]?\d+)/([-]?\d+\.\d+|[-]?\d+)', s)for i in result:s = s.replace(f'{i[0]}/{i[1]}', f'{float(i[0]) / float(i[1])}')while '*' in s:result = re.findall('([-]?\d+\.\d+|[-]?\d+)\*([-]?\d+\.\d+|[-]?\d+)', s)for i in result:if float(i[0]) < 0 and float(i[1]) < 0:s = s.replace(f'{i[0]}*{i[1]}', f'+{float(i[0]) * float(i[1])}')else:s = s.replace(f'{i[0]}*{i[1]}', f'{float(i[0]) * float(i[1])}')result = re.findall('([-]?\d+\.\d+|[-]?\d+)', s)x = 0for i in result:x += float(i)s = str(x)return sdef cal(s):s = s.replace(' ', '')while '(' in s or ')' in s:ret = re.findall('\(([^()]+?)\)', s)for i in ret:s = s.replace(f'({i})', count(i))s = s.replace('--', '+')else:s = count(s)return s

重构原则

  1. 重构代码要分析原代码,找出重复代码将其封装成函数。

  2. 注释清晰、完整,便于将来升级迭代。

  3. 代码模块化,模块化可以提高代码复用率,隔离bug。

重构后的代码

import redef cal(s):'''处理含括号四则运算字符串主程序。先计算小括号里的内容,将该内容替换成计算后的值,最终计算出结果。'''def count(s):'''计算不含括号的四则运算,先计算乘除法,再计算加减法'''while '/' in s:result = re.findall('([-]?\d+\.\d+|[-]?\d+)/([-]?\d+\.\d+|[-]?\d+)', s)for i in result:s = s.replace(f'{i[0]}/{i[1]}', f'{float(i[0]) / float(i[1])}')while '*' in s:result = re.findall('([-]?\d+\.\d+|[-]?\d+)\*([-]?\d+\.\d+|[-]?\d+)', s)for i in result:if float(i[0]) < 0 and float(i[1]) < 0:  # 处理负数乘负数的特殊情况s = s.replace(f'{i[0]}*{i[1]}',  f'+{float(i[0]) * float(i[1])}')else:s = s.replace(f'{i[0]}*{i[1]}',  f'{float(i[0]) * float(i[1])}')result = re.findall('([-]?\d+\.\d+|[-]?\d+)', s)x = 0for i in result:x += float(i)s = str(x)return sdef symbol(s):'''处理四则运算字符串中出现连续多个+号和-号'''while '++' in s:s = s.replace('++', '+')while '+-' in s:s = s.replace('+-', '-')while '-+' in s:s = s.replace('-+', '-')while '--' in s:s = s.replace('--', '+')return s

    s = s.replace(' ', '')while '(' in s or ')' in s:ret = re.findall('\(([^()]+?)\)', s)for i in ret:s = s.replace(f'({i})', count(i))s = symbol(s)  # 处理剥去括号后出现减去负号的情况else:s = count(s)return sprint(cal('10 - 3 * ( (50-30 +(-10/5) * (9-2*5/3 + 7 /3*99/4*2020 +10 * 789/15 )) - (-4*3)/ (16-3*2) )'))print(cal('10-3*(20-10+(-10/5)*27/3/3-(-100)/(10-3*5))'))print(cal('10-3*(20-10+(-10/5)*27/3/3-(-100)/(10-3*5))+(-2.5*-12)'))

请注意函数内定义函数的写法,例如上面的count和symbol这2个函数只有cal函数会调用,因此定义在cal函数内部是最佳选择。这样封装性更好,运行效率更高。
在一个函数内调用其他函数时会优先从自己的命名空间内找名字,找不到再去外层,再找不到再去全局找。所以定义在函数内部的名字查找到的速度是最快的。

看完上述内容,你们掌握python中怎么实现代码重构的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注行业资讯频道,感谢各位的阅读!