使用包的别名时,为什么从包导入无效? [英] Why is importing from a package invalid when the aliased name of package is used?
问题描述
为了更加清楚,请考虑一个小例子:
To make it more clear, consider a numpy example :
import numpy as np
from numpy import array
这按预期工作.但是呢:
This works as expected. But what about this:
from np import array
输出为:
Traceback (most recent call last)
<ipython-input-21-d5c81fa93e5f> in <module>()
----> 1 from np import array
ModuleNotFoundError: No module named 'np'
一旦将导入的模块numpy的别名设置为np
,我是否只能使用np导入其他内容?
Once I have set the alias of the imported module numpy as np
, shouldn't I be able to import something else using np only?
此外,两者的id()
是相同的-numpy
和np
都指相同的事物.
Also, the id()
of both is the same -- both numpy
and np
refer to the same thing.
推荐答案
即使将模块导入为np
,模块名称仍为numpy
.
The module name is still numpy
, even after you import the module as np
.
import … as …
语法的主要作用是:
np = internal_import_module('numpy')
因此,np
只是用来引用numpy
模块的本地名称.如果查看模块名称np
,您会发现它仍然是'numpy'
:
So the np
is just the local name that get used to refer to the numpy
module. If you look at the module name of np
, you can see that it’s still 'numpy'
:
>>> import numpy as np
>>> np.__name__
'numpy'
现在,在评估另一个import语句时,根本不使用模块的本地名称.所以您的from numpy import array
基本上就是这样:
Now, the local name of a module is not being used at all when another import statement is being evaluated. So your from numpy import array
is basically just this:
array = internal_import_module('numpy').array
此处array
还是numpy
模块内部array
成员的本地名称.但是,它不是np
模块内部的成员,因为根本就没有该名称的模块.
Here array
is again just a local name for the array
member inside of the numpy
module. It is however not a member inside of the np
module because there simply isn’t a module with that name.
这篇关于使用包的别名时,为什么从包导入无效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!