[英]python - import subpackage from a package not working?
I have the following files: 我有以下文件:
pack/__init__.py
pack/subpack/__init.__py
pack/subpack/mod2.py
And the following code fails on the last line: 以下代码在最后一行失败:
from pack import * #should import everything
print subpack #NameError: name 'subpack' is not defined
I would expect the subpackage to be imported - why is there a difference, and how can I overcome it? 我希望导入子包 - 为什么会有差异,我怎样才能克服它?
Important: by "overcoming" I mean being able to refer to
subpack
without needing to write pack.subpack
all the time. 重要:通过“克服”我的意思是能够引用
subpack
而无需一直编写pack.subpack
。
You need to add 你需要添加
__all__ = ["mod1", "subpack"]
to pack/__init__.py
. pack/__init__.py
。 Without this line, mod1
would not be imported either, so I wonder what is going on there. 没有这一行,
mod1
也不会导入,所以我想知道那里发生了什么。 See also the relevant section in Guido's tutorial . 另请参阅Guido教程中的相关部分 。
Try adding "import subpack" in pack/__init__.py
尝试在
pack/__init__.py
添加“import subpack”
If you have __all__
declared, make sure 'subpack' appears there. 如果你声明
__all__
,请确保在那里出现'subpack'。
Alternative suggestion for Python 3 is: Python 3的另一个建议是:
# pack/__init__.py
from . import subpack
And, as already was mentioned, if __all__
is declared, then add 'subpack'
here. 并且,如前所述,如果声明
__all__
,则在此处添加'subpack'
。
And do not forget, that if you need NOT only: 不要忘记,如果您不仅需要:
print subpack
but also: 但是也:
print subpack.mod2
then you need make similar operations in pack/subpack/__init.__py
file 那么你需要在
pack/subpack/__init.__py
文件中进行类似的操作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.