导入父包后调用模块

亚什万德巴梅尔

我一直试图弄清楚如何在导入其父包后调用模块。

目录结构如下所示:

.
├── 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在我的脚本中使用,以便将来我可以回忆起我filepkg而不是some_other_pkg.

巨蟒

在你__init__.pymain/pkg你将不得不导入file

# pkg/__init__.py

import pkg.file

# EDIT: if the import above does not work, use this instead

from . import file

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章