[英]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 LibAddParticipant
我from 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.