为什么从 scipy 导入空间工作,而导入 scipy 后 scipy.spatial 不起作用? [英] Why does from scipy import spatial work, while scipy.spatial doesn't work after import scipy?
问题描述
我想在我的代码中使用 scipy.spatial.distance.cosine
.如果我执行诸如 import scipy.spatial
或 from scipy import spatial
之类的操作,我可以导入 spatial
子模块,但是如果我只是 importscipy
调用 scipy.spatial.distance.cosine(...)
导致以下错误:AttributeError: 'module' object has no attribute 'spatial'
.
第二种方法有什么问题?
导入包不会自动导入子模块.您需要显式导入子模块.
例如import xml
不导入子模块xml.dom
有一个像 os.path
这样的例外.(os
模块本身将子模块导入其命名空间)
I would like to use scipy.spatial.distance.cosine
in my code. I can import the spatial
submodule if I do something like import scipy.spatial
or from scipy import spatial
, but if I simply import scipy
calling scipy.spatial.distance.cosine(...)
results in the following error: AttributeError: 'module' object has no attribute 'spatial'
.
What is wrong with the second approach?
Importing a package does not import submodule automatically. You need to import submodule explicitly.
For example, import xml
does not import the submodule xml.dom
>>> import xml
>>> xml.dom
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'dom'
>>> import xml.dom
>>> xml.dom
<module 'xml.dom' from 'C:\Python27\lib\xml\dom\__init__.pyc'>
There's an exception like os.path
. (os
module itself import the submodule into its namespace)
>>> import os
>>> os.path
<module 'ntpath' from 'C:\Python27\lib\ntpath.pyc'>
这篇关于为什么从 scipy 导入空间工作,而导入 scipy 后 scipy.spatial 不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!