从NumPy,matplotlib包导入python子模块有什么区别 [英] what is the difference between importing python sub-modules from NumPy, matplotlib packages

查看:69
本文介绍了从NumPy,matplotlib包导入python子模块有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试使用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模块(例如matplotlibnumpy)都有一个__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's __init__.py doesn't include the statement import pyplot.
  • numpy's __init__.py does include import random, on line 176.

这篇关于从NumPy,matplotlib包导入python子模块有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆