2012-07-27 6 views
18

Der CodeEs gibt eine Klasse matplotlib.axes.AxesSubplot, aber das Modul matplotlib.axes hat kein Attribut AxesSubplot

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

der Ausgang

<class 'matplotlib.axes.AxesSubplot'> 

dann den Code

import matplotlib.axes 
matplotlib.axes.AxesSubplot 
gibt

löst die Ausnahme

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

Zusammenfassend gibt es eine Klasse matplotlib.axes.AxesSubplot, aber das Modul matplotlib.axes hat kein Attribut AxesSubplot. Was zu Hölle ist hier los?

Ich benutze Matplotlib 1.1.0 und Python 2.7.3.

+0

Gibt es ein tatsächliches Problem Sie versuchen, mit diesem zu lösen, oder ist diese Frage nur Neugier? – Julian

+3

@Julian: Es ist "nur Neugier". Ich glaube, dass Neugier ein besserer Entwickler ist. – user763305

Antwort

19

Heh. Das liegt daran, ist keine AxesSubplot Klasse .. bis man benötigt wird, wenn man von SubplotBase gebaut wird. Dies wird durch eine Magie in axes.py getan:

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 

So ist es im laufenden Betrieb gemacht hat, aber es ist eine Unterklasse von 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

Sollte nicht die Klasse erstellt werden, wenn ich das erste Code-Snippet ausführen, und als ein Attribut von Matplotlib.axes vorhanden sein, wenn ich das zweite Code-Snippet ausführen? – user763305

+3

Es * wird * erstellt, aber es wird nicht auf Modulebene gespeichert. Suchen Sie in 'matplotlib.axes._subplot_classes': Sie sollten' {matplotlib.axes.Axes: matplotlib.axes.AxesSublplot} 'sehen. Beachten Sie, dass in der Factory-Funktion die 'new_class' zum' _subplot_classes' Dictionary hinzugefügt wird. – DSM

Verwandte Themen