您好,登錄后才能下訂單哦!
python中怎么實現(xiàn)代碼重構(gòu),相信很多沒有經(jīng)驗的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。
重構(gòu)前
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
重構(gòu)代碼要分析原代碼,找出重復(fù)代碼將其封裝成函數(shù)。
注釋清晰、完整,便于將來升級迭代。
代碼模塊化,模塊化可以提高代碼復(fù)用率,隔離bug。
import redef cal(s):'''處理含括號四則運(yùn)算字符串主程序。先計算小括號里的內(nèi)容,將該內(nèi)容替換成計算后的值,最終計算出結(jié)果。'''def count(s):'''計算不含括號的四則運(yùn)算,先計算乘除法,再計算加減法'''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: # 處理負(fù)數(shù)乘負(fù)數(shù)的特殊情況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):'''處理四則運(yùn)算字符串中出現(xiàn)連續(xù)多個+號和-號'''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) # 處理剝?nèi)ダㄌ柡蟪霈F(xiàn)減去負(fù)號的情況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)'))
請注意函數(shù)內(nèi)定義函數(shù)的寫法,例如上面的count和symbol這2個函數(shù)只有cal函數(shù)會調(diào)用,因此定義在cal函數(shù)內(nèi)部是最佳選擇。這樣封裝性更好,運(yùn)行效率更高。
在一個函數(shù)內(nèi)調(diào)用其他函數(shù)時會優(yōu)先從自己的命名空間內(nèi)找名字,找不到再去外層,再找不到再去全局找。所以定義在函數(shù)內(nèi)部的名字查找到的速度是最快的。
看完上述內(nèi)容,你們掌握python中怎么實現(xiàn)代碼重構(gòu)的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。