关于python:有一个类matplotlib.axes.AxesSubplot,但是模块matplotlib.axes没有属性AxesSubplot

There is a class matplotlib.axes.AxesSubplot, but the module matplotlib.axes has no attribute AxesSubplot

代码

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

给出输出

1
<class 'matplotlib.axes.AxesSubplot'>

然后是代码

1
2
import matplotlib.axes
matplotlib.axes.AxesSubplot

引发异常

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

总而言之,有一个类matplotlib.axes.AxesSubplot,但是模块matplotlib.axes没有属性AxesSubplot。 到底是怎么回事?

我正在使用Matplotlib 1.1.0和Python 2.7.3。


嘿。 这是因为在从SubplotBase构建一个类之前,没有一个AxesSubplot类。 这是通过axes.py中的一些魔术完成的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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的子类:

1
2
3
4
5
6
7
8
9
>>> 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


查看DSM所说的另一种方式:

1
2
3
4
5
6
7
8
9
10
In [1]: from matplotlib import pyplot as plt                                                                                                                                                                      

In [2]: type(plt.gca()).__mro__                                                                                                                                                                                    
Out[2]:
(matplotlib.axes._subplots.AxesSubplot,
 matplotlib.axes._subplots.SubplotBase,
 matplotlib.axes._axes.Axes,
 matplotlib.axes._base._AxesBase,
 matplotlib.artist.Artist,
 object)

使用dunder方法解析顺序,您可以找到某个类的所有继承。