作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有两个模块在一个包下形成循环导入
/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
最佳答案
import
做三件事:
sys.modules
中没有的模块(通常来自磁盘) .import
范围内分配一个变量允许访问指定的模块。有很多技巧:
import a.b
分配一个变量 a
, 这样你就可以写 a.b
就像在导入中一样。import a.b as c
分配 c
成为模块 a.b
, 不是 a
和以前一样。from a import b
可以选择 a
的模块或任何其他属性 .sys.modules
中的相关条目在导入开始时创建。第 2 点和第 4 点用通告 import a.b as b
解释了故障: 循环导入直接进入第 3 步,但随后导入尝试从尚未发生的外部 导入的第 2 步加载属性。
from
歧义used to cause同样的麻烦,但是一个special fallback查看sys.modules
在 3.5 中添加以支持这种情况。同样的方法可能适用于 import a.b as b
,但这还没有发生。
关于python - "import pkg.a as a"和 "from pkg import a"有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49784828/
我是一名优秀的程序员,十分优秀!