2017-04-19 3 views
0

Ich versuche, dies zu implementieren: https://stackoverflow.com/a/12025554/7718153 für Matplotlib, aber etwas schief geht.Wie Funktionen mit getattr in Python aufrufen?

import matplotlib.pyplot as plt 

if condition1: 
    q='plot' 
elif condition2: 
    q='logy' 
elif condition3 
    q='loglog' 

m = globals()['plt']() 
TypeError: 'module' object is not callable 

plot_function = getattr(m, q) #it doens't make it to this line 

Ich will es, dies zu tun:

if condition1: 
    plt.plot(...) 
elif condition2: 
    plt.logy(...) 
elif condition3: 
    plt.loglog(...) 

Weiß jemand, was ich falsch gemacht?

Edit: Es tut mir leid, ich hatte meinen Code in der falschen Reihenfolge. Es ist jetzt behoben.

Edit2:

Dies ist der Code, wo es origionally kam aus:

def plot(self): 
    assert self.plotgraph == True 
    plt.figure(1) 
    plt.rcParams.update({'font.size': 40}) 
    plt.figure(figsize=(150, 70)) 
    plt.suptitle('alpha = '+str("{0:.2f}".format(self.alpha))) 


    j=len(self.seeds) 
    for k in range(9*j): 
     plt.subplot(3,3*j,k+1) 
     g=k%(3*j) 
     if k<3*j: 
      q='plot' 
     elif 3*j<=k<6*j: 
      q='logy' 
     elif 6*j<=k: 
      q='loglog' 
     m = globals()['plt']() 
     plot_function = getattr(m, q) 
     if g<2*j: 
      for i in range(j): 
       if (2*i)<=g%j*2<(2*(i+1)): 
        seed_type=' seed: '+ str(i+1) 
        seed=(i+1) 
     else: 
      for i in range(j): 
       if g%j == i: 
        seed_type=' seed: '+ str(i+1) 
        seed=(i+1) 

     if g<2*j: 
      if g%2==0: 
       set_type=' train-set' 
       plot_function(np.array(self.index),np.array(self.plotlist[seed*2+0])) 
      else: 
       set_type=' test-set' 
       plot_function(np.array(self.index),np.array(self.plotlist[seed*2+1])) 
     else: 
      set_type=' train-test dist' 
      plot_function(np.array(self.index),np.array(self.plotlist[seed*2+0]-np.array(self.plotlist[seed*2+1]))) 

     plt.grid(True) 
     plt.title(q+set_type+seed_type) 
    plt.tight_layout() 
    plt.savefig("plot1() " +str(self.nodes[1])+' hidden nodes, alpha='+ str("{0:.2f}".format(self.alpha)) + '.png') 
    plt.clf() 
    plt.close() 

Antwort

2

m = globals()['plt']() das gleiche wie plt() ist. plt ist ein Modul, so dass es nicht abrufbar ist. Ich denke, du willst:

m = globals()['plt'] 
plot_function = getattr(m, q) 
plot_function() # call this one! 

Mit dem gesagt ... Dieses Design scheint unnötig komplex. Warum nicht:

if condition1: 
    plt.plot() 
elif condition2: 
    plt.logy() 
elif condition3: 
    ... 
+0

Es wirft den Fehler, wenn ich versuche, m zu definieren. Es ist Teil einer größeren Schleife. Ich werde meinen ursprünglichen Beitrag aktualisieren. –

+0

Es funktioniert! Danke für die schnelle Antwort. –