为什么在python中会出现这种attributerror?

2024-05-14 03:26:20 发布

您现在位置:Python中文网/ 问答频道 /正文

有一件事,我不明白。

为什么会这样

import scipy # happens with several other modules, too. I took scipy as an example now...

matrix = scipy.sparse.coo_matrix(some_params)

产生此错误:

AttributeError: 'module' object has no attribute 'sparse'

Tags: importanmodulesexampleaswithscipymatrix
3条回答

当对象的属性不可用时引发AttributeError

attribute reference是主键,后跟句点和名称:

attributeref ::= primary "." identifier

要返回该对象的有效属性列表,请使用^{},例如:

dir(scipy)

所以你可能需要做的很简单:import scipy.sparse

因为你导入的是scipy,而不是sparse。尝试from scipy import sparse

这是因为scipy模块没有任何名为sparse的属性。只有在import scipy.sparse时才定义该属性。

当您只是import scipy时,子模块不会自动被导入;您需要显式地导入它们。大多数包也是这样,尽管包可以选择导入它自己的子模块。(例如,如果scipy/__init__.py包含语句import scipy.sparse,则无论何时导入scipy都将导入sparse子模块。)

相关问题 更多 >