2016-04-29 48 views
-1

我正在使用一個類,它允許我分析已有數據的數組並將其作爲數組返回。Python - 調用類函數來分析數組時出錯

這是我正在使用的類的一部分。

import numpy as np 
from scipy.integrate import quad 
import matplotlib.pyplot as plt 
from scipy import interpolate 

class MassFunction: 

    def __init__(self, h=0.7, Omega_m=.27, sigma8=.809, n=0.95, rho_c=1.35972365653e11, delta_c=1.686): 
     """ 
     @param h: hubble parameter. 
     @param omega_m: current matter fraction of universe. 
     @param sigma8: Value of variance of density field with spherical smoothing at 8 Mpc/h 
     @param n: spectral scalar index for primordial power spectrum 
     @param delta_c: amplitude of perturbation at collapse using linear theory. 
     @param rho_c: critical density of universe in Msun/Mpc 
     """ 
     self.h = h 
     self.Omega_m = Omega_m 
     self.n = n 
     self.delta_c = delta_c 
     self.rho_m = rho_c*Omega_m/self.h**2 
     self.sigma8 = sigma8 

    def NofM(self,masses, numbins, boxsize): 
     """ 
     Produce mass function data for N(m). Fractional number density of halos in 
     mass range (m,m+dm). Integrates to total number of halos/volume. 
     @param masses: list of all masses in Msun/h 
     @param numbins: number of bins to use in histogram 
     @param boxsize: Size of box in MPc/h. 
     @return: [x-axis in log10(mass), y-axis in log10(N(m)), xlabel, ylabel] 
     """ 
     logmasses = np.log10(masses) 
     hist, r_array = np.histogram(logmasses, numbins) 
     dlogM = r_array[1]-r_array[0] 
     x_array = r_array[1:] - .5*dlogM 
     dM = 10.**r_array[1:]-10.**r_array[0:numbins] #Mass size of bins in non-log space. 
     volume = np.float(boxsize**3) # in MPc^3 
     return [x_array, np.log10(hist/volume/dM)] 

該課程的其餘部分要長得多,但在這種情況下使用其他功能並不是必需的。

在我試圖調用它的時候,我輸入了它,並嘗試將它與所提供的大量數組一起使用。

import matplotlib.pyplot as plt 
import numpy as np 
import MassFunction 

# This is just the array of data 
halomass3 = halos3['GroupMass'] * 1e10/0.704 # in units of M_sol h^-1 

MassFunction.MassFunction.NofM(halomass3,100, 75000) 

林返回與此錯誤unbound method NofM() must be called with MassFunction instance as first argument (got ndarray instance instead)

我不是最熟悉使用類,或調用類,因爲這使用它們是我的第一次。我是否打電話給__init__並設置參數,還是錯過了更多的東西?

如果我遺漏了任何必要的信息。請告訴我!

回答

1

您需要首先創建類的實例。

MassFunction myinstance = MassFunction() 
myinstance.NofM(halomass3,100, 75000) 
2

函數NofM不依賴於self因此它可以定義爲類的方法

類方法使用裝飾器@classmethod創建,使它們不需要第一個隱含的參數self

更新的方法如下:

@classmethod 
def NofM(cls, masses, numbins, boxsize): 
    ... 

類方法接收類(CLS)爲隱式的第一個參數,就像一個實例方法接收實例(個體)。現在

,你可以調用類方法如下:

>>> MassFunction.MassFunction.NofM(halomass3, 100, 75000)