我一直在努力弄清楚如何在导入父包后调用模块。
目录结构如下:
.
├── 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
有没有一种方法可以像 pkg.file
一样调用 file
而无需执行 from main.pkg import file
?
P.S.:我想在我的脚本中使用 pkg.file
以便将来我可以记忆起我从 调用了
而不是 file
>pkgsome_other_pkg
。
最佳答案
在 main/pkg
的 __init__.py
中,您必须导入 file
:
# pkg/__init__.py
import pkg.file
# EDIT: if the import above does not work, use this instead
from . import file
关于python - 在导入父包后调用模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68141238/