2012-07-27 22 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

相關問題