gpt4 book ai didi

python - "import pkg.a as a"和 "from pkg import a"有什么区别?

转载 作者:行者123 更新时间:2023-11-28 18:13:41 24 4
gpt4 key购买 nike

我有两个模块在一个包下形成循环导入

/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 afrom 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做三件事:

  1. 查找并加载 sys.modules 中没有的模块(通常来自磁盘) .
  2. 每个新加载的模块完成执行后,将其分配为其包含包(如果有)的属性。
  3. import范围内分配一个变量允许访问指定的模块。

有很多技巧:

  1. import a.b分配一个变量 a , 这样你就可以写 a.b就像在导入中一样。
  2. import a.b as c分配 c成为模块 a.b , 不是 a和以前一样。
  3. from a import b可以选择 a 的模块或任何其他属性 .
  4. 循环导入的第 1 步立即“成功”,因为 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com