2016-04-29 2 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) 

Imが、これはそれらを使用して私の最初の時間ですので、私は、クラスを使用して、またはクラスを呼び出すに最も精通していないよ、このエラーで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

関数NofMselfに依存しないので、クラスメソッドと定義できます。

クラスメソッドは、最初の暗黙の引数selfを必要としないように、@classmethodデコレータで作成されます。

更新方法を次のよう

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

クラスメソッドは、インスタンスメソッドがインスタンス(自己)を受信するだけのように、クラス(CLS)として暗黙の最初の引数を受け取ります。あなたが最初のクラスのインスタンスを作成する必要が

>>> MassFunction.MassFunction.NofM(halomass3, 100, 75000) 
関連する問題