2012-07-27 94 views
18

代码有一类matplotlib.axes.AxesSubplot,但模块matplotlib.axes有没有属性AxesSubplot

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。

+0

有没有你想用此方法解决一个实际问题,或者这个问题只是好奇心? – Julian 2012-07-27 15:17:57

+3

@Julian:这只是“好奇心”。我相信好奇心让你成为更好的开发者。 – user763305 2012-07-27 15:21:16

回答

19

嘿。那是因为没有AxesSubplot类..直到有一个需要时,当一个从SubplotBase构建。这是通过一些魔法axes.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 
+1

当我运行第一个代码片段时,不应该创建该类,并且当我运行第二个代码片段时,它将作为matplotlib.axes的属性出现? – user763305 2012-07-27 15:24:47

+3

它*被*创建,但它不存储在模块级别。查看'matplotlib.axes._subplot_classes':你应该看到'{matplotlib.axes.Axes:matplotlib.axes.AxesSubplot}'。请注意,在工厂函数中,'new_class'被添加到'_subplot_classes'字典中。 – DSM 2012-07-27 15:25:59

相关问题