简体   繁体   中英

from module import vs import big_module [python]

For some reason, this works:

from sklearn import svm

but this one does not

import sklearn  

sklearn.svm.LinearSVC()

saying module svm is not a subnodule of sklearn.

shouldn't they be the same thing?

I've created a file system layout as follows.

[9:29pm][wlynch@watermelon layout] tree
.
├── __init__.py
└── sklearn
    ├── __init__.py
    └── svm
        └── __init__.py

[9:31pm][wlynch@watermelon layout] cat __init__.py 
[9:31pm][wlynch@watermelon layout] cat sklearn/__init__.py
[9:31pm][wlynch@watermelon layout] cat sklearn/svm/__init__.py
def LinearSVC():
    pass

Let's run python :

[9:29pm][wlynch@watermelon layout] python
Python 2.7.5 (default, Mar  9 2014, 22:15:05) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sklearn
>>> sklearn.svm
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'svm'

>>> import sklearn.svm
>>> sklearn.svm.LinearSVC()
>>>

Often, a python library designer will resolve this issue, by having sklearn/__init__.py include the line import svm .

The first code works if svm is a variable in sklearn OR svm is a submodule of sklearn

from sklearn import svm

The second code only works if sklearn imports svm and holds it as a variable in its namespace

import sklearn
sklearn.svm.LinearSVC()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM