简体   繁体   English

如何从另一个文件(在另一个文件夹中)包含 class - python

[英]How to include class from another file(in another folder) - python

I have a python file in the location 'lib/lib_add_participant.py'.And I declared a class in the file.我在“lib/lib_add_participant.py”位置有一个 python 文件。我在文件中声明了一个 class。

Now I want to call the class functions from the file call_participant.py.现在我想从文件 call_participant.py 中调用 class 函数。

I tried this code from lib/lib_add_participant.py import LibAddParticipantfrom lib/lib_add_participant.py import LibAddParticipant

Its not worked.Please correct me(I am coming from Ruby).它不起作用。请纠正我(我来自 Ruby)。

If your file structure is as follows:如果你的文件结构如下:

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

In this case, your __init__.py files can be empty , if you like (or they can define any number of things - see this fine answer from Alex Martelli for more details.在这种情况下,您的__init__.py文件可以是的,如果您愿意(或者它们可以定义任意数量的东西 - 请参阅Alex Martelli 的这个很好的答案以获取更多详细信息。

then you can add it by using然后你可以通过使用添加它

from .lib.lib_add_participant import LibAddParticipant

However, if call_participant.py is your end script, then this tactic will not work, because you "can't do a relative import in a non-package", as the interpreter will tell you.但是,如果call_participant.py是您的最终脚本,那么这种策略将不起作用,因为您“不能在非包中进行相对导入”,正如解释器会告诉您的那样。 In that case, your best bet (in my opinion, at least) is to make lib into a package in your python path (either in your site-packages directory, or in a path referred to by your pythonpath environment variable).在这种情况下,你最好的选择(至少在我看来)是在你的 python 路径中(在你的站点包目录中,或者在你的pythonpath环境变量引用的路径中)将lib变成 package 。

Assuming lib is in a directory listed in your PYTHONPATH , try假设lib位于PYTHONPATH中列出的目录中,请尝试

from lib.lib_add_participant import LibAddParticipant

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM