Why does this AttributeError in python occur?

后端 未结 4 1088
孤街浪徒
孤街浪徒 2020-12-01 07:41

There is one thing, that I do not understand.

Why does this

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


        
相关标签:
4条回答
  • 2020-12-01 07:49

    This happens because the scipy module doesn't have any attribute named sparse. That attribute only gets defined when you import scipy.sparse.

    Submodules don't automatically get imported when you just import scipy; you need to import them explicitly. The same holds for most packages, although a package can choose to import its own submodules if it wants to. (For example, if scipy/__init__.py included a statement import scipy.sparse, then the sparse submodule would be imported whenever you import scipy.)

    0 讨论(0)
  • 2020-12-01 08:04

    AttributeError is raised when attribute of the object is not available.

    An attribute reference is a primary followed by a period and a name:

    attributeref ::= primary "." identifier

    To return a list of valid attributes for that object, use dir(), e.g.:

    dir(scipy)
    

    So probably you need to do simply: import scipy.sparse

    0 讨论(0)
  • 2020-12-01 08:07

    The default namespace in Python is "__main__". When you use import scipy, Python creates a separate namespace as your module name. The rule in Pyhton is: when you want to call an attribute from another namespaces you have to use the fully qualified attribute name.

    0 讨论(0)
  • 2020-12-01 08:11

    Because you imported scipy, not sparse. Try from scipy import sparse?

    0 讨论(0)
提交回复
热议问题