如果这样输入:
import sklearn
sklearn.datasets.load_iris()
则会报错:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-1-9edfa66b871f> in <module>
1 import sklearn
----> 2 sklearn.datasets.load_iris()
AttributeError: module 'sklearn' has no attribute 'datasets'
而这样的话:
from sklearn import datasets
#或者
#from sklearn import *
sklearn.datasets.load_iris()
则不会报错
这是由于:when you import a package, only variables/functions/classes in the __init__.py
file of that package are directly visible, not sub-packages or modules.
直接import包的话,只有在__init__.py文件中的变量,函数,类可以直接被使用,包中的子包或者模块则不行
when you load the sub-package datasets
by doing from sklearn import datasets
it is automatically added to the namespace of the package sklearn
. This is one of the lesser-known "traps" of the Python import system.
Also, note that if you look at the __init__.py
for sklearn
you will see 'datasets'
as a member of __all__
, but this only allows you to do:
In [1]: from sklearn import *
In [2]: datasets
Out[2]: <module 'sklearn.datasets' from '/home/ethan/.virtualenvs/test3/lib/python3.5/site-packages/sklearn/datasets/__init__.py'>
摘抄自这个问答