gpt4 book ai didi

python - 在 Python 类中继承 Cython 类

转载 作者:行者123 更新时间:2023-12-01 04:42:28 29 4
gpt4 key购买 nike

我有两个用 cython 编写的类,我想在 python 的类中使用它们。

位置.pyx

import numpy as np
cimport numpy as np
cimport cython
cpdef double std_G,v=4.3e-9, 299792.458

cdef class cosmo(object):
cdef public double o_m, o_l, h, w, o_r, G, v
def __init__(self,double o_m = 0.3, double o_l = 0.7, double h = 0.7, double w = -1, double o_r = 0., double G = std_G):

self.o_m = o_m
self.o_l = o_l
self.o_r = o_r
self.h = h
self.w = w
self.G = G
self.v = v

def __copy__(self):

return cosmo(o_m = self.o_m, o_l = self.o_l, h = self.h, w = self.w, o_r = self.o_r, G = self.G)

property H0:
def __get__(self):
return 100*self.h

property M_solar:
def __get__(self):
return 1.989e30

property Mpc_to_m:
def __get__(self):
return 3.0856e22;

def hubble2(self, double z):
cdef double inv_a
inv_a = 1.+z
return (self.o_r*inv_a**4 + self.o_m*inv_a**3 + \
self.o_l*(inv_a**(3*(1+self.w))) + (1 - self.o_m - self.o_l - self.o_r)*inv_a**2)*self.H0**2

property hubble_length:
def __get__(self):
return self.v / self.H0

def rc(self, double z):

return 3.*self.hubble2(z)/(8*np.pi*self.G)

cdef class PositionsD(object):

cdef double [:] _x
property x:
def __get__(self):
return np.array(self._x)
def __set__(self, np.ndarray[DTYPE_T, ndim=1] x):
self._x = x

cdef double [:] _y
property y:
def __get__(self):
return np.array(self._y)
def __set__(self, np.ndarray[DTYPE_T, ndim=1, mode='c'] y):
self._y = y

def __init__(self, np.ndarray[DTYPE_T, ndim=2, mode='c'] positions):
self._x = positions[:,0]
self._y = positions[:,1]

虽然我想在 modelfit 类中使用 PositionsD 类,而 modelfit 会继承 PositionsD 的属性:

from position import *
import numpy as np
class modelfit(PositionsD):
cosmo = cosmo()
def __init__(self):
super(modelfit,self).__init__(shear_pos)

self.arcsec2rad = 2*np.pi/180./3600.
self.shear_g = None
self.shear_pos = shear_pos *self.arcsec2rad
self.shear_z = None
self.halo_pos = None
self.halo_z = None
self.sigma_g = np.sqrt(np.std(self.shear_g[:,1]**2+self.shear_g[:,2]**2))/np.sqrt(2)
self.n_model_evals = 0
self.gaussian_prior_theta = [{'mean' : 14, 'std': 0.5}]
self.rho_c= cosmo.rc(self.halo_z)

但我收到以下错误消息:

>>> x=np.array([[0.3,-0.1],[1,3.4]])
>>> mf=modelfit(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __init__() takes exactly 1 argument (2 given)

我不知道我做错了什么。有什么建议吗?

最佳答案

在当前的类定义中,__init__ 不需要任何参数。这就是为什么当您调用 mf=modelfit(x) 时会引发错误。由于 shear_pos 不会以其他方式定义,我假设您打算将其作为类初始化中的参数传递。如果是这样,你应该写:

class modelfit(PositionsD):
cosmo = cosmo()
def __init__(self, shear_pos):
super(modelfit,self).__init__(shear_pos)
...

关于python - 在 Python 类中继承 Cython 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30279889/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com