我不太熟悉在python中编写类,我正在尝试为我的应用程序修改一个编写的类。问题是我想将halo_pos
参数作为以下NFW
类的输入:
class NFW(object):
_req_params = { 'mass' : float , 'conc' : float , 'redshift' : float }
_opt_params = { 'halo_pos' :[float,float] , 'omega_m' : float , 'omega_lam' : float }
_single_params = []
_takes_rng = False
_takes_logger = False
def __init__(self, mass, conc, redshift, halo_pos,
omega_m=None, omega_lam=None, cosmo=None):
self.M = float(mass)
self.c = float(conc)
self.z = float(redshift)
self.halo_pos.x = float(halo_pos[0])
self.halo_pos.y = float(halo_pos[1])
self.cosmo = cosmo
如果我为halo_pos
传递以下参数的输入
>>> Xpos.value
array(235.0)
>>> type(Xpos.value)
<type 'numpy.ndarray'>
>>> Ypos.value
array(340.0)
omega_matter=0.23;omega_lambda=0.77
然后当我尝试使用给定的输入调用NFW类时,我收到以下错误消息:
nfw = nfw_halo.NFWHalo(mass=M,conc=concentration,redshift=z_halo,halo_pos=[Xpos,Ypos],omega_m=omega_matter,omega_lam=omega_lambda)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "nfw_halo.py", line 156, in __init__
self.halo_pos.x = float(halo_pos[0])
AttributeError: 'NFWHalo' object has no attribute 'halo_pos'
我应该如何为我的班级定义 halo_pos 以避免出现错误消息?
答案 0 :(得分:1)
您没有声明您在 init 部分中指定的halo_pos变量。
class NFW(object):
_req_params = { 'mass' : float , 'conc' : float , 'redshift' : float }
_opt_params = { 'halo_pos' :[float,float] , 'omega_m' : float , 'omega_lam' : float }
_single_params = []
_takes_rng = False
_takes_logger = False
halo_pos = None
def __init__(self, mass, conc, redshift, halo_pos,
omega_m=None, omega_lam=None, cosmo=None):
self.M = float(mass)
self.c = float(conc)
self.z = float(redshift)
self.halo_pos = halo_positions(halo_pos)
self.cosmo = cosmo
print(str(self.halo_pos.x),str(self.halo_pos.y))
class halo_positions(object):
x = None
y = None
def __init__(self,positions):
self.x = positions[0]
self.y = positions[1]
if __name__ == '__main__':
nfw = NFW(mass=1.23,conc=2.34,redshift=3.45,halo_pos=[4.56,5.67],omega_m=1.111,omega_lam=1.222)
一旦 init 完成,你的delclaration self.halo_pos.x和self.halo_pos.y就会被清除。