我正在使用一个类,它允许我分析我拥有的数据数组并将其作为数组返回。
以下是我正在使用的课程部分。
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__
并设置参数,还是我错过了更多的东西?
如果我遗漏了任何必要的信息。请让我知道!
答案 0 :(得分:2)
函数NofM
并不依赖self
,因此可以将其定义为类方法。
使用@classmethod
装饰器创建类方法,使它们不需要第一个隐式参数self
。
按如下方式更新方法:
@classmethod
def NofM(cls, masses, numbins, boxsize):
...
类方法接收类(cls)作为隐式的第一个参数,就像实例方法接收实例(self)一样。
现在,您可以按如下方式调用类方法:
>>> MassFunction.MassFunction.NofM(halomass3, 100, 75000)
答案 1 :(得分:1)
您需要先创建该类的实例。
MassFunction myinstance = MassFunction()
myinstance.NofM(halomass3,100, 75000)