如何手动重构 python 项目?

How do I manually refactor a python project?

随着我对如何不构建编码项目的了解越来越多,我意识到我必须四处移动很多东西才能将它们放在正确的位置。

例如,我有一个 "practice data science" 项目,我只是将各种不相关的代码转储到其中。我的目录如下所示:

 - PyCharm Projects
     - data-science-at-home
         - birth_names.py
         - birthplots.py
         - genedata.py
         - etc.

现在,我正在学习如何将您的代码分成 "packages" 相关模块(.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

说明: 在英文中,以上行的意思是:从该脚本所在的目录中,导入名称为 'bn'

的文件 'birth_names'

.表示本地目录。