2016-09-16 216 views
1

我看過其他帖子,但沒有找到有效的答案!python絕對導入子模塊失敗

文件結構

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

回答

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'>