When I try to use pyplot from matplotlib:

import matplotlib

print matplotlib.pyplot # just checking

It gives me AttributeError: 'module' object has no attribute 'pyplot'

It can be solved with:

import matplotlib.pyplot

But what I am really confused with is,

import numpy

print numpy.random

gives me

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.

解决方案

For the definitive tutorial, read this.

But for your specific case, it looks like this is what's happening:

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.

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.

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐