What is the difference between “import pkg.a as a” and “from pkg import a”?
我有两个模块组成一个包下的循环导入
1 2 3 4 | /test __init__.py a.py b.py |
A.Py
1 2 3 | import test.b def a(): print("a") |
B.Py
1 2 3 | import test.a def b(): print("b") |
但是当我从python交互式解释器中执行"import test.a"时,它会抛出attributeError:module"test"没有属性"a"。
1 2 3 4 5 6 7 8 | >>> 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' |
但当我把它改成
那么有什么区别呢?
我在用Python3.5
编辑1:
正如@davis herring所问,python2的行为不同。使用
1 2 3 4 | 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 |
但是,当使用
1 2 3 4 5 6 7 8 9 10 11 | 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 |
有很多技巧:
点2和点4解释了循环