当我这样做时...
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/