You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

导入Cython对象至Python文件时,调用cdef方法遇属性不存在错误求助

问题原因

错误的核心是:Cython中用cdef定义的类方法只能在Cython代码内部访问,Python解释器无法识别这些方法,所以会提示属性不存在。

解决方案

有两种方式可以让Python调用Cython类的方法:

1. 将方法改为def定义

def定义的方法对Python完全可见,兼容Python调用,但性能比cdef稍差。修改后的parameters.pyx代码:

cdef class Parameters:
    cdef int myInt

    def __init__(self, int myInt):
        self.myInt = myInt

    def set_myInt(self, int value):
        self.myInt = value

    def get_myInt(self):
        return self.myInt

2. 使用cpdef定义方法

cpdef会同时生成C级别的cdef方法和Python可见的def方法,兼顾性能与Python可访问性,适合需要在Cython内部高效调用、同时也要给Python使用的场景:

cdef class Parameters:
    cdef int myInt

    def __init__(self, int myInt):
        self.myInt = myInt

    cpdef set_myInt(self, int value):
        self.myInt = value

    cpdef int get_myInt(self):
        return self.myInt
验证修改

修改完parameters.pyx后,重新编译Cython文件(比如通过setup.py或cythonize命令),再运行model.py即可正常调用方法。

内容的提问来源于stack exchange,提问作者user58925

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 02:51:13