2

I found a really weird behaviour when trying to import the module pyplot from matplotlib. First it says it does not exist, but after importing pylab (another matplotlib module), it suddently works!

>>> import matplotlib
>>> matplotlib.__version__
'1.2.1'
>>> matplotlib.pyplot
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'pyplot'
>>> import pylab
>>> matplotlib.pyplot
<module 'matplotlib.pyplot' from '/Library/Python/2.7/site-packages/matplotlib/pyplot.pyc'>

Anyone else has this behaviour in his/her computer?


** This happened on a OS X Mountain Lion, running Python 2.7. I installed matplotlib with pip.

4

1 回答 1

4

In general, to access a module within a package, you must import that module. You can't just import the package and access the module with dot syntax. Just do from matplotlib import pyplot (or import matplotlib.pyplot if you really like typing dots).

The reason it works after importing pylab is that pylab imports pyplot, after which pyplot is available as an attribute of the enclosing package matplotlib.

Basically, if you do import package, you can't expect you will be able to do package.module. But if you do import package and from package import module, then you can do package.module.

于 2013-03-29T18:40:14.843 回答