导入python包时跳过目录的级别 [英] Skip over levels of a directory when importing python package
本文介绍了导入python包时跳过目录的级别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的目录结构如下:
Folder_in_PYTHONPATH/
├── Package1
│ ├── __init__.py
│ ├── src
│ │ ├── Class1.py
│ │ ├── Class2.py
│ │ └── __init__.py
│ └── test
│ └── testfile.py
├── Package2
│ ├── __init__.py
│ ├── src
│ │ ├── Class1.py
│ │ ├── Class2.py
│ │ └── __init__.py
│ └── test
│ ├── test1.py
│ └── test2.py
.
.
.
当我从这个文件夹导入东西时,我需要总是输入
When I import things from this folder, I need to always type
import Package1.src.Class1
有什么方法可以设置我的 __init__.py
以便我可以输入
Is there any way to set up my __init__.py
so that I can just type
import Package1.Class1
相反?
推荐答案
将它们添加到包的 __init__.py
文件中,使其看起来像:
Add them into your packages' __init__.py
files so they look like:
from src import Class1
from src import Class2
查看文档
我建议将 *.py 文件放在其包的顶级文件夹中,以获得您所追求的 import Package_1.Class1
行为.单元测试可以保留在它们自己的文件夹中以将它们分开.
I would recommend putting the *.py files in the top level folder of their package to get the import Package_1.Class1
behaviour you are after. The unit tests can stay in their own folder to keep them separate.
这篇关于导入python包时跳过目录的级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文