为什么在导入scipy后,from scipy import spatial可以正常工作,而scipy.spatial无法工作?

29
我想在我的代码中使用scipy.spatial.distance.cosine。如果我像import scipy.spatialfrom scipy import spatial这样做,我可以导入spatial子模块,但是如果我只是import scipy,调用scipy.spatial.distance.cosine(...)会导致以下错误:AttributeError: 'module' object has no attribute 'spatial'

第二个方法有什么问题?

2
@alKid和@falsetru给出了很好的答案,你应该接受其中一个。特别是对于scipy来说,我们不导入所有子包的原因是有很多子包,并且许多子包具有大型扩展模块,需要消耗相当长的时间来加载。大多数程序不需要加载所有的scipy,所以如果我们总是导入所有的子包,那么这将给所有程序增加很多额外的开销。 - Robert Kern
“alKid”和“falsetru”提供的答案不准确,且有误导性。原因在于包的__init__文件。Scipy的__init__文件没有导入其模块,而像Numpy这样的其他一些包的__init__文件则导入了它们的模块。请参见重复线程中更好的答案:https://dev59.com/NJDea4cB1Zd3GeqPcoXC - Ravaging Care
4个回答

32

导入一个包不会自动导入子模块。您需要显式地导入子模块。

例如,import xml 不会导入子模块 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'>

os.path 这样有一个例外。(os 模块本身将子模块导入其命名空间中)

>>> import os
>>> os.path
<module 'ntpath' from 'C:\Python27\lib\ntpath.pyc'>

13

这是因为Scipy是一个,不是一个模块。当你导入一个包时,你实际上没有加载里面的模块,因此package.module会导致错误。

然而,import package.module会起作用,因为它加载了模块,而不是包。

这是大多数导入语句的标准行为,但也有一些例外。

在Python 3中,urllib的情况与上述相同:

>>> import urllib
>>> dir(urllib)
['__builtins__', '__cached__', '__doc__', '__file__', '__initializing__', '__loader__', '__name__', '__package__', '__path__', 'error', 'parse', 'request', 'response']

看吧?那里没有子模块。要访问其子模块,我们需要请求子模块:

>>> import urllib.request
>>> 

希望这个简单的解释能够帮助到你!


2

使用以下代码进行导入:

import scipy.spatial # worked.

替代

import scipy # not working

我尝试过,它有效。


-1
使用Scipy 1.2.1版本来解决这个问题......

3
请问您需要翻译的内容是:“Always elaborate your answer. In this case, you can say what betterment is available in 1.2.1 version or the bug fixed, etc.”吗?如果是的话,我的翻译如下:请详细阐述您的答案。在这种情况下,您可以说明1.2.1版本提供了哪些改进或修复了哪些漏洞等。 - SibiCoder
1
欢迎来到SO。不幸的是,您的答案既没有回答OP的问题“第二种方法有什么问题?”也是错误的。即使使用scipy 1.4.1,第二种方法仍会导致AttributeError:module 'scipy' has no attribute 'spatial' - David Buck

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接