python中怎么实现代码重构

发布时间:2021-07-10 15:22:22 作者:Leah
来源:亿速云 阅读:110

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中怎么实现代码重构的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

推荐阅读:
  1. QT之计算器代码重构(六)
  2. 代码重构规范

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python

上一篇:怎么自动备份Linux/Unix服务器的数据

下一篇:python中魔术方法有哪些

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》