我有两个模块在包下形成循环导入
/test
__init__.py
a.py
b.py
a.py
import test.b
def a():
print("a")
b.py
import test.a
def b():
print("b")
但是当我从 python 交互式解释器中执行“import test.a”时,它会抛出 AttributeError: module 'test' has no attribute 'a'
>>> import test.a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "test/a.py", line 2, in <module>
import test.b as b
File "test/b.py", line 1, in <module>
import test.a as a
AttributeError: module 'test' has no attribute 'a'
但是当我将其更改为from test import a
and from test import b
,效果很好。
那么区别是什么呢?
我使用的是python3.5
Edit 1:
正如@Davis Herring 所问,python2 的行为有所不同。
使用时import test.a as a
格式没有抛出错误。
Python 2.7.12 (default, Dec 4 2017, 14:50:18)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import test.a
然而,当使用from test import a
它抛出错误
Python 2.7.12 (default, Dec 4 2017, 14:50:18)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import test.a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "test/a.py", line 2, in <module>
from test import b
File "test/b.py", line 1, in <module>
from test import a
ImportError: cannot import name a