从NumPy,matplotlib包导入python子模块有什么区别 [英] what is the difference between importing python sub-modules from NumPy, matplotlib packages
问题描述
当我尝试使用matplotlib
中的pyplot
时:
import matplotlib
print matplotlib.pyplot # just checking
它给了我AttributeError: 'module' object has no attribute 'pyplot'
可以通过以下方式解决:
It can be solved with:
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并不是那么专业,因此要求一个答案.
What is the difference between two cases? pyplot
cannot be called in the first example, but random
was in the second. I think it's related with some kind of packages and modules. But I'm not such a professional to the python, thus asking for an answer.
推荐答案
对于权威教程,阅读.
但是对于您的特定情况,看来是这样:
But for your specific case, it looks like this is what's happening:
每个基于目录的python模块(例如matplotlib
和numpy
)都有一个__init__.py
文件,该文件确定将什么内容带入模块的顶级范围.默认情况下(__init__.py
为空),范围不存在.
Every directory-based python module (like matplotlib
and numpy
) has an __init__.py
file, which determines what is brought into the module's top-level scope. By default (when __init__.py
is empty), nothing is in scope.
但是,某些模块(如numpy
)决定通过向__init__.py
添加import语句来将功能提升到顶层.即使您仅显式导入了numpy
,这也将这些子模块纳入了范围.
However, some modules (like numpy
) have decided to hoist functionality into the top-level by adding import statements to __init__.py
. This brings those submodules into scope, even if you've only explicitly imported numpy
.
要检查我们的假设,让我们看一下消息源!
To check our assumptions, let's look at the source!
- matplotlib的
__init__.py
不包括语句import pyplot
. - numpy的
__init__.py
确实包含,在第176行.
- matplotlib's
__init__.py
doesn't include the statementimport pyplot
. - numpy's
__init__.py
does includeimport random
, on line 176.
这篇关于从NumPy,matplotlib包导入python子模块有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!