我看过其他帖子,但没有找到有效的答案!
文件结构
my_package/
__init__.py -- empty
test/
__init__.py -- empty
test1.py
故障
from my_package import test
test.test1
给出
AttributeError: 'module' object has no attribute test
以下通行证
from my_package.test import test1
# or
import my_package.test.test1
from my_package import test
# now this works
test.tes1
<module 'my_package.test.test1' from ...
我有
from __future__ import absolute_import
在所有文件中,并使用python2.7
答案 0 :(得分:1)
导入包时(如test
),模块(如test1
)不会自动导入(除非您在__init__.py
中放置了一些特殊代码)。这与导入模块不同,模块的内容在模块名称空间中可用。与Python标准库的xml.etree.ElementTree
模块进行比较:
>>> import xml
>>> xml.etree
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'etree'
>>> from xml import etree
>>> etree.ElementTree
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'ElementTree'
>>> from xml.etree import ElementTree
>>> ElementTree.ElementTree
<class 'xml.etree.ElementTree.ElementTree'>