python - 如何手动重构 python 项目?
问题描述
随着我越来越多地了解如何不构建编码项目,我意识到我必须移动很多东西才能将它们放在正确的位置。
例如,我有一个“实践数据科学”项目,我只是将各种不相关的代码倒入其中。我的目录如下所示:
- 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
错误。出于某种原因,一切都在编译,并且被认为不存在的模块被重复使用,但是那个错误弹出窗口真的很烦人。
我注意到 move 重构只工作了大约一半的时间,并且在它工作时似乎会引起很多问题。也许手动做这种事情会更好,但我不明白所有 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
解释:英文中,上面一行的意思是:从这个脚本所在的目录,导入名为'bn'的文件'birth_names'
.
表示本地目录。
推荐阅读
- django - 将 Wagtail 与现有 Django 项目集成后访问 Wagtail cms 页面时出现 404 错误
- javascript - 我需要根据屏幕类型为一个组件执行不同的 API 调用
- azure - Azure 函数
- laravel - channel vs channel_name - 私人频道的 Laravel Echo 和 Laravel 变量名
- python - 如何对依赖于前一行的熊猫代码进行矢量化?
- javascript - 调度程序播放在 10 分钟后停止 (discord.js)
- assembly - 我无法打开文件以通过程序进行阅读。汇编器
- javascript - Javascript Set,传递给函数时引用中断
- android - 我正在使用 react native,当我使用 npx react-native run-android 运行我的项目时,出现此错误
- xsl-fo - XSL-FO 中的 N 页序列