gpt4 book ai didi

python - 为什么有些包需要用 'from' 导入,而其他包需要用 'import' 导入?

转载 作者:太空宇宙 更新时间:2023-11-04 07:05:42 28 4
gpt4 key购买 nike

当我这样做时...

import numpy as np

...我可以使用它但是...

import pprint as pp

...不能,因为我需要这样做...

from pprint import pprint as pp

还有 __import__(str(module)) 可能更多隐藏在文档中

我读过一些书,'import module' or 'from module import'例如,但答案更有针对性地选择使用哪个。另外,python-how-to-import-other-python-files只是提供更多关于利弊的见解。

有人能解释一下为什么会有差异吗?使用不同类型的导入时幕后发生了什么,它们是如何工作的?

最佳答案

导入模块时,python 需要在文件系统中找到它,并将其分配给模块中的某个变量名。各种形式允许您分配不同的本地名称(“作为某物”)或进入模块并将其内部对象之一分配给本地名称(“来自...”)。

import numpy                           # imports numpy and names it "numpy"
import numpy as np # imports numpy and names it "np"
from pprint import pprint # imports pprint anonymously, finds an
# object in pprint called "pprint"
# and names it "pprint"
from pprint import pprint as pp # imports pprint anonymously, finds an
# object in pprint called "pprint"
# and names it "pp"

关于python - 为什么有些包需要用 'from' 导入,而其他包需要用 'import' 导入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49101423/

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