[英]How do I manually refactor a python project?
隨着我越來越多地學習如何不構建編碼項目,我意識到我必須做很多事情才能將它們放在正確的位置。
例如,我有一個“實踐數據科學”項目,我只是將各種無關的代碼轉儲到其中。 我的目錄如下所示:
- PyCharm Projects
- data-science-at-home
- birth_names.py
- birthplots.py
- genedata.py
- etc.
現在,我正在學習如何將您的代碼分為與之相關的模塊“包”(.py文件,對嗎?)。
因此,在我的IDE(PyCharm)中,我創建了一個新程序包,然后將重構的.py文件移動到其中:
- PyCharm Projects
- data-science-at-home
- birth-names
- birth_names.py
- birthplots.py
- package_genestuff
- genedata.py
因此,我發現我的所有代碼仍然可以按預期進行編譯和運行,但是在我的graphingutility.py文件的頂部(我import birthnames as bn
,我得到了一個no module named birthnames
錯誤。 由於某種原因,所有內容都在編譯,並且原本不存在的模塊正在重復使用,但是錯誤彈出窗口確實令人討厭。
我注意到,移動重構只能工作大約一半的時間,並且在工作時似乎會引起很多問題。 也許手動做這種事情會更好,但是我不理解所有的xml,config和git文件的內部工作原理,每次我抽動手指時似乎都會改變……什么是合適的方法?完成了嗎
編輯:根據要求,實際代碼:
import birth_names as bn
import matplotlib.pyplot as plt
def myPlotter(ax, data1, data2, param_dict):
out = ax.plot(data1, data2, **param_dict)
return out
def plotRankAndScores(name, gender):
files = bn.getPaths()
print(files)
x1, y1 = bn.getAllRanks(name, gender, files)
x2, y2 = bn.getAllScores(name, gender, files)
ave = bn.getAverageRank(name, gender, select=False, filez=files)
# fig, (ax1, ax2) = plt.subplots(2, 1)
# myPlotter(ax1, x1, y1, {'linestyle': '-.', 'color': 'red'})
# myPlotter(ax2, x2, y2, {'linestyle': '--'})
fig2, (ax3, ax4) = plt.subplots(2, 1, sharex='all', figsize=(10, 10))
plt.xlabel("Year")
ax3.plot(x1, y1, 'b')
ax3.set_ylabel("Rank")
ax3.axhline(y1.mean(), label='average = {}'.format(ave), linestyle='--', color='red')
ax3.legend()
ax4.plot(x2, y2, 'b')
ax4.set_ylabel("Number of Births")
ax4.axhline(y2.mean(), label='average = {}'.format(y2.mean()), linestyle='--', color='red')
ax4.legend()
plt.suptitle("Name Rank and Number of Births by Year")
plt.show()
if __name__ == '__main__':
plotRankAndScores("Wesley", "M")
將頂行更改為: from . import birth_names as bn
from . import birth_names as bn
說明:用英語,上一行意思是:從此腳本所在的目錄中導入名稱為“ bn”的文件“ birth_names”
的.
表示本地目錄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.