[英]How to import Python file universally from the same folder and from outer?
I have hierarchy of files:我有文件层次结构:
folder文件夹
| |
classes班级
| |
class1.py类1.py
class2.py类2.py
test_class2.py test_class2.py
main.py主文件
Sorry, I can't find how to tab text.抱歉,我找不到如何标记文本。 Main.py and classes folder is in the same folder.
Main.py 和 classes 文件夹在同一个文件夹中。
Main.py imports from class2.py from classes.class2 import someclass
. Main.py 从 class2.py 进口
from classes.class2 import someclass
。
The class2.py imports from class1.py from classes.class1 import someanotherclass
. class2.py 从 class1.py 进口
from classes.class1 import someanotherclass
。
This works perfectly in case of running main.py.这在运行 main.py 的情况下非常有效。 The problem is if I want to test class2.py in the folder 'classes', I always need to change import to
from class1.py import someanotherclass
.问题是如果我想在文件夹“classes”中测试 class2.py,我总是需要将 import 更改为
from class1.py import someanotherclass
。 So is there any universal way to import it in both cases, so as for main.py and class2.py work properly?那么在这两种情况下是否有任何通用的方法可以导入它,以便 main.py 和 class2.py 正常工作?
I would assume that relative imports
is what you are looking for: https://docs.python.org/3/reference/import.html#package-relative-imports我假设您正在寻找
relative imports
: https://docs.python.org/3/reference/import.html#package-relative-imports
main.py主文件
from classes.class2 import someclass
classes/class2.py类/class2.py
from .class1 import someanotherclass
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.