当我尝试使用时pyplot
from matplotlib
:
import matplotlib
print matplotlib.pyplot # just checking
它给了我AttributeError: 'module' object has no attribute 'pyplot'
可以用以下方法解决:
import matplotlib.pyplot
但我真正困惑的是,
import numpy
print numpy.random
给我<module 'numpy.random' from '/Applications/Canopy.app/appdata/canopy-1.0.3.1262.macosx-x86_64/Canopy.app/Contents/lib/python2.7/site-packages/numpy/random/__init__.pyc'>
两种情况有什么区别?pyplot
在第一个示例中无法调用,但是random
是在第二。我认为这与某种包和模块有关。但我对python不是那么专业,因此寻求答案。
对于最终的教程,读这个 https://docs.python.org/2/tutorial/modules.html.
但对于您的具体情况,看起来发生的事情是这样的:
每个基于目录的 python 模块(例如matplotlib
and numpy
)有一个__init__.py
文件,它确定将哪些内容带入模块的顶级范围。默认情况下(当__init__.py
为空),范围内没有任何内容。
但是,某些模块(例如numpy
)决定通过添加 import 语句来将功能提升到顶层__init__.py
。这会将这些子模块纳入范围,即使您只是显式导入numpy
.
为了验证我们的假设,让我们看看来源!
-
matplotlib 的__init__.py https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/__init__.py不包括该声明
import pyplot
.
-
numpy's __init__.py https://github.com/numpy/numpy/blob/master/numpy/__init__.py#L176确实包括
import random
,第 176 行。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)