【问题标题】:How to include class from another file(in another folder) - python如何包含来自另一个文件的类(在另一个文件夹中) - python
【发布时间】:2011-10-09 16:02:24
【问题描述】:

我在“lib/lib_add_participant.py”位置有一个 python 文件。我在文件中声明了一个类。

现在我想从文件 call_participant.py 中调用类函数。

我试过这个代码from lib/lib_add_participant.py import LibAddParticipant

它不起作用。请纠正我(我来自 Ruby)。

【问题讨论】:

    标签: python class python-3.x


    【解决方案1】:

    假设lib 位于您的PYTHONPATH 中列出的目录中,请尝试

    from lib.lib_add_participant import LibAddParticipant
    

    【讨论】:

    • 如果 lib 在 $PYTHONPATH 中列出,它将是:lib_add_participant import LibAddParticipant。如果 lib 在 $PYTHONPATH 中列出的目录之一中,那么您的代码将起作用,但前提是那里也有 __init__.py 文件。
    【解决方案2】:

    如果你的文件结构如下:

    myproject/
        __init__.py
        call_participant.py
        lib/
            __init__.py
            lib_add_participant.py
    

    在这种情况下,您的__init__.py 文件可以为空,如果您愿意(或者它们可以定义任意数量的东西 - 请参阅this fine answer from Alex Martelli 了解更多详细信息。

    然后你可以使用添加它

    from .lib.lib_add_participant import LibAddParticipant
    

    但是,如果call_participant.py 是您的最终脚本,那么这种策略将不起作用,因为您“不能在非包中进行相对导入”,正如解释器会告诉您的那样。在这种情况下,您最好的选择(至少在我看来)是将lib 放入您的python 路径中的一个包中(在您的站点包目录中,或者在您的pythonpath 环境变量引用的路径中)。

    【讨论】:

    • 一个错误:应该有__init__.py而不是__init.py
    • 糟糕!很好的捕捉 - 我对 tpynig 的理解也很不错。
    • 我没有创建 init.py 文件。现在请告诉我里面的内容是什么。我搜索了谷歌并没有得到任何东西。跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-04
    相关资源
    最近更新 更多