将 Cython 对象导入到 Python 文件中

问题描述 投票:0回答:1

我有两个文件中的代码,其中一个导入另一个文件。 文件1

参数.pyx

cdef class Parameters:
    cdef int myInt

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

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

    cdef int get_myInt(self):
        return self.myInt

文件2

模型.py

from parameters import Parameters

def single_run():
    parameters = Parameters(10)
    print(parameters.get_myInt())  # Access it using the get_myInt method

    parameters.set_myInt(100)  # Use the set_myInt method to modify it
    print(parameters.get_myInt())  # Access it again to see the modified value

我收到以下错误:

“parameters.Parameters”对象没有属性“set_myInt”

python class cython
1个回答
0
投票

您无法在其他纯 Python 代码中调用使用

cdef
定义的函数/方法(请参阅此处),因此您必须将
cdef
定义的方法切换为仅使用
def
cpdef
:

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

更新

如果您需要方法的

cdef
版本,您可以拥有
def
版本,它本质上只是充当
cdef
版本的包装器,例如,

cdef class MyClass:
    cdef int myInt

    def __init__(self, int myInt):
        # stuff

    def my_complex_function(self, value):
        """
        Wrapper to C-version of function.
        """

        return self._my_complex_functon(value)

    cdef int _my_complex_function_c(self, int value):
        # do stuff
        ...
© www.soinside.com 2019 - 2024. All rights reserved.