当我这样做时......
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只是提供了更多关于利弊的见解。
有人能否解释为何存在差异;在使用不同类型的导入以及它们如何工作时幕后发生了什么?
答案 0 :(得分:3)
不同之处在于pprint模块包含一个名为pprint的函数。所以当你跑步的时候
import pprint as pp
您需要调用pp.pprint
来引用该函数。
Numpy暴露在顶层,其中所有的函数/类都嵌套在其中。
答案 1 :(得分:3)
当你说
时当我这样做时......
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]
不需要将from
与pprint
一起使用,也不要将from
与numpy
一起使用。 from
导入只是从模块中提取特定内容;例如,from pprint import pprint as pp
会将pprint.pprint
函数设为pp
。您基本上不需要以某种方式执行导入。
答案 2 :(得分:3)
导入模块时,python需要在文件系统中找到它并将其分配给模块中的某个变量名。各种表单允许您分配不同的本地名称(&#34;作为某些内容&#34;)或进入模块并将其内部对象之一分配给本地名称(&#34;来自...&#34;)
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"