【问题标题】:Python Can't Import Class From Parent Directory?Python 无法从父目录导入类?
【发布时间】:2021-10-23 00:11:29
【问题描述】:

我是 Python 新手,所以我可能看不到明显的解决方案。我在网上搜索了一个解决方案,每个人似乎都有相同的答案。我正在尝试从 Python 中的父目录导入文件。我来自 JavaScript,您只需键入 import Function from '../ParenetDirectory/FileThatIncludesFunction' 即可导入该模块。我访问过的每个网站都说你必须在你的怪诞path 中包含父目录才能导入它。我们是认真的吗?我假设我遗漏了一些东西,因为在我看来,Python 将有一种更优雅的方式来做到这一点,而不是编辑你该死的 path 以从父目录导入一个类。请告诉我有,或者向我解释为什么没有。

【问题讨论】:

    标签: python import dry modularity


    【解决方案1】:

    您可以通过使用 sys 模块并将所需目录添加到其路径来做到这一点。

    "../ParenetDirectory/FileThatIncludesFunction.py":

    def Function():
        return 'Hello, World!'
    

    main.py:

    import sys
    
    sys.path.append('../ParenetDirectory')
    
    from FileThatIncludesFunction import Function
    
    print(Function())
    

    请注意,如果您想通过 cmd 运行,请确保 cmd 中的文件夹正是 main.py 文件所在的位置。

    【讨论】:

    • 谢谢@ThisIsMatin。正如你所描述的那样有效。正如我所提到的,这感觉很笨拙,但这似乎是在 Python 中实现它的方式。
    猜你喜欢
    • 2013-11-09
    • 1970-01-01
    • 2016-12-27
    • 2012-07-08
    • 2020-03-21
    • 2021-12-25
    • 2021-08-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多