我一直试图弄清楚如何在导入其父包后调用模块。
目录结构如下所示:
.
├── main
│ └── pkg
│ └── file.py
└── another_main
注意:所有包都包含__init__.py
文件并设置了所有必要的路径变量。我没有在这里展示它,因为这只是一个虚拟结构。
如果我做:
from main import pkg
pkg.file
这不起作用并抛出 AttributeError: module 'pkg' has no attribute 'file'
但如果我首先这样做:
from main.pkg import file
之后我可以这样做:
from main import pkg
pkg.file # --> Now this doesn't throw AttributeError
有没有一种方法,我可以打电话file
一样pkg.file
没有做from main.pkg import file
?
PS:我想pkg.file
在我的脚本中使用,以便将来我可以回忆起我file
从pkg
而不是some_other_pkg
.
在你__init__.py
的main/pkg
你将不得不导入file
:
# pkg/__init__.py
import pkg.file
# EDIT: if the import above does not work, use this instead
from . import file
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句