30

コード

import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
print type(ax)

出力を与える

<class 'matplotlib.axes.AxesSubplot'>

次に、コード

import matplotlib.axes
matplotlib.axes.AxesSubplot

例外を発生させます

AttributeError: 'module' object has no attribute 'AxesSubplot'

要約すると、クラスはmatplotlib.axes.AxesSubplotありますが、モジュールmatplotlib.axesには属性がありませんAxesSubplot。一体何が起こっているのですか?

私は Matplotlib 1.1.0 と Python 2.7.3 を使用しています。

4

2 に答える 2

32

へー。これは、クラス存在しないためです..から構築されたときに必要になるまで.. これは のいくつかの魔法によって行われます:AxesSubplotSubplotBaseaxes.py

def subplot_class_factory(axes_class=None):
    # This makes a new class that inherits from SubplotBase and the
    # given axes_class (which is assumed to be a subclass of Axes).
    # This is perhaps a little bit roundabout to make a new class on
    # the fly like this, but it means that a new Subplot class does
    # not have to be created for every type of Axes.
    if axes_class is None:
        axes_class = Axes

    new_class = _subplot_classes.get(axes_class)
    if new_class is None:
        new_class = new.classobj("%sSubplot" % (axes_class.__name__),
                                 (SubplotBase, axes_class),
                                 {'_axes_class': axes_class})
        _subplot_classes[axes_class] = new_class

    return new_class

そのため、オンザフライで作成されますが、次のサブクラスですSubplotBase

>>> import matplotlib.pyplot as plt
>>> fig = plt.figure()
>>> ax = fig.add_subplot(111)
>>> print type(ax)
<class 'matplotlib.axes.AxesSubplot'>
>>> b = type(ax)
>>> import matplotlib.axes
>>> issubclass(b, matplotlib.axes.SubplotBase)
True
于 2012-07-27T15:19:13.903 に答える