为什么有些包需要使用'from'导入,而其他包需要使用"导入"导入?



当我这样做时...

import numpy as np

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

import pprint as pp

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

from pprint import pprint as pp

文档中还有__import__(str(module))甚至可能隐藏的内容

我已经阅读了一些内容,例如"导入模块">

或"从模块导入",但答案更针对选择使用哪个。此外,python-how-to-import-other-python-files只是提供了更多关于优缺点的见解。

有人可以阐明为什么存在差异;使用不同类型的导入时幕后发生了什么以及它们是如何工作的?

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

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"

不同之处在于 pprint 模块包含一个名为 pprint 的函数。所以当你跑步时 import pprint as pp 您需要调用pp.pprint来引用该函数。

然而,Numpy 在顶层公开,它的所有函数/类都嵌套在其中。

当你说

当我这样做时...

import numpy as np

。它是可调用的

你错了。 numpy是不可调用的。它是一个模块。

>>> import numpy as np
>>> np()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'module' object is not callable

模块提供的函数是可调用的:

>>> np.arange(5)
array([0, 1, 2, 3, 4])

同样,pprint模块不可调用。它是一个模块。pprint.pprint函数是可调用的:

>>> import pprint as pp
>>> pp.pprint([1, 2, 3])
[1, 2, 3]
没有必要将

frompprint一起使用,或者不将fromnumpy一起使用。 from导入只是从模块中提取特定内容;例如,from pprint import pprint as pp为您提供pprint.pprint功能作为pp。基本上,您永远不需要以一种或另一种方式执行导入。

最新更新