繁体   English   中英

python绝对导入子模块失败

[英]python absolute import of submodule fails

我看过其他帖子,但没有找到有效的答案!

文件结构

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

当您导入包(如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'>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM