我有两个模块在一个包下形成了循环引用。
然而,当使用
/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
和from test import b
时,它可以正常工作。
那么区别在哪里呢?
我正在使用Python3.5
编辑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