cythton,引用其它未知数量不定的pyx时,进行列表化时使用时不能引用cdef,只能引用cpdef方法

问题遇到的现象和发生背景
因为需要需要从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()不加强制类型可以正常执行

你是不是可以自己重写一个引入类的列表化方法,把类型转换和类引用合成一个方法

cdef定义的函数,变量在python环境中是访问不了的,要么提供一个def的包装方法,要么用cpdef。cpdef只用于定义函数,

速度比cdef稍慢,主要因为cpdef定义的类函数支持重载,调用的时候需要查找虚函数表,cpdef同时生成供cython和python

利用泛型试试

不知道你描述是不是 import 一个字符串控制的库
试试 这种方法

>>> tmp='os'

>>> import tmp
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named tmp

解决这个问题可以使用如下方法:

>>> module1=__import__(tmp)
>>> print module1.__doc__

https://blog.csdn.net/weixin_39614750/article/details/111454260?spm=1005.2026.3001.5635&utm_medium=distribute.pc_relevant_ask_down.none-task-blog-2~default~OPENSEARCH~Rate-4.pc_feed_download_top3ask&depth_1-utm_source=distribute.pc_relevant_ask_down.none-task-blog-2~default~OPENSEARCH~Rate-4.pc_feed_download_top3ask

飘过~分钱~~!