首页 > 解决方案 > 如何手动重构 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")

标签: pythonpackagedirectory-structure

解决方案


将第一行更改为: from . import birth_names as bn

解释:英文中,上面一行的意思是:从这个脚本所在的目录,导入名为'bn'的文件'birth_names'

.表示本地目录。


推荐阅读