问题遇到的现象和发生背景
因为需要需要从B.pyx引用C.pyx类,因C类数量、名字有很多,B类里只能列表化
b_list =[DemoCC(self.his)......]
但是当b_list[0].get_his_111()引用方法时,只能引用cpdef方法,如果要引用cdef方法只能在b_list[0]前面加强制类型
(<DemoCC>self.b_list[0]).get_his_111()
但实际使用中C类名字根据情况有很多,不能这样使用,有没有一种方法可以列表化未知的pyx类,且正常引用该类cdef方法
问题相关代码,请勿粘贴截图
A.py
import pyximport
pyximport.install()
from B import DemoBB
bb =DemoBB([1,2,3])
B.pyx
# cython: language_level=3
from C cimport DemoCC
cdef class DemoBB():
cdef list b_list
cdef DemoCC cc
def __init__(self,his):
self.cc = DemoCC(his)
#此处可以正常返回[1, 2, 3]
print(self.cc.get_his_111())
self.b_list = [DemoCC(his)]
#列表 类 引用 cdef 会报错
#AttributeError: 'B.DemoBB' object has no attribute 'his'
#print(self.b_list[0].get_his_111())
#列表 类 引用 cdef 前面加<DemoCC>正常返回[1, 2, 3]
print(<DemoCC>self.b_list[0].get_his_111())
#列表 类 引用 cpdef 正常返回[1, 2, 3],但没有cdef高效,不使用
print(self.b_list[0].get_his_222())
"""
实际运用中因为引用的DemoCC未知可能是DemoFF,而且数量不定,
使用时列表也不好加<DemoCC>,使用cpdef也会降低速度
有没有一种方法可以存储未知的pyx类,而且使用时可以引用cdef
"""
c.pyx
# cython: language_level=3
cdef class DemoCC():
def __init__(self,his):
self.his = his
cdef list get_his_111(self):
return self.his
cpdef list get_his_222(self):
return self.his
c.pxd
# cython: language_level=3
cdef class DemoCC():
cdef list his
cdef list get_his_111(self)
cpdef list get_his_222(self)
运行结果及报错内容
B.pyx
#列表 类 引用 cdef 会报错
#AttributeError: 'C.DemoCC' object has no attribute 'get_his_111'
#print(self.b_list[0].get_his_111())
我的解答思路和尝试过的方法
在self.b_list中每个类加一个识别码,再判断强制类型,但此方法太复杂,实际操作中每增加一个C类,要修改的地方很多
self.b_list = [ [DemoCC(his),1] ]
print(self.class_get_his(0)
cdef list class_get_his(self,int x):
cdef int code
code = self.b_list[x][1]
if code==1:
return (<DemoCC>self.b_list[x][0]).get_his_111()
我想要达到的结果
B.pyx 引用 C.pyx 列表化时能正常引用C.pyx里的cdef方法
让上面这行self.b_list[0].get_his_111()不加强制类型可以正常执行