导入scipy模块有什么问题,是bug吗?
好的,我觉得我很难用文字来解释这个问题,所以我这里有一段ipython会话的代码片段,我在里面导入了scipy,目的是为了构建一个稀疏矩阵。
In [1]: import scipy as sp
In [2]: a = sp.sparse.lil_matrix((5,5))
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
/home/liveuser/<ipython-input-2-b5a55fc2d0ac> in <module>()
----> 1 a = sp.sparse.lil_matrix((5,5))
AttributeError: 'module' object has no attribute 'sparse'
In [3]: import scipy.sparse as spar
In [4]: ax = spar.lil_matrix((5,5))
In [5]: a = sp.sparse.lil_matrix((5,5)) # you are kidding me?
In [6]: a
Out[6]:
<5x5 sparse matrix of type '<type 'numpy.float64'>'
with 0 stored elements in LInked List format>
In [7]: ax
Out[7]:
<5x5 sparse matrix of type '<type 'numpy.float64'>'
with 0 stored elements in LInked List format>
在这里发生了什么呢?为什么我第一次导入稀疏子模块的时候,不能用sp来构建稀疏矩阵?但当我按照代码片段的方式导入后,sp和spar这两个变量都可以用来构建稀疏矩阵。(我猜它们只是指向同一个对象的引用)
我重现了这个python默认的命令行环境(所以这并不是ipython特有的情况)。
到底发生了什么?这是故意设计成这样的?如果是的话,请详细解释一下。还是说这是个bug呢?
我的系统是Fedora 16 KDE-scientific,64位。
1 个回答
10
这是Python导入模块时的一个特性,不是SciPy的问题。你可以这样做:
from scipy import sparse [as sp]
或者这样:
import scipy.sparse [as sp]
(这里的[]
表示这个部分是可选的)。
简单来说,import
语句需要知道模块的“真实”名称,而不是通过import as
语句创建的缩写名称。