我正在尝试使用 Cython 将 python 类转换为 C 类以提高时间复杂度。我最常用的变量是在 init 方法中定义的类变量,因此我想将它们定义为 cdef double。我已经尝试了我能找到的所有方法,但没有任何方法可以让我转换代码。看来这应该是这样做的方法:
class Wall(object):
cdef double min_x, max_x, a, b, c
def __init__(self, start, stop):
self.min_x = min(start[0], stop[0])
self.max_x = max(start[0], stop[0])
self.a = (stop[1]-start[1])/(stop[0]-start[0])
self.b = -1
self.c = start[1]-self.a*start[0]
但是我收到以下错误:
Error compiling Cython file: ------------------------------------------------------------ ... class Wall(object): cdef double min_x, max_x, a, b, c ^ ------------------------------------------------------------ wall_class_cy.pyx:9:9: cdef statement not allowed here
我做错了什么?
您需要将类变量公开并为该类提供 C 声明。试试这个:
cdef class Wall(object):
cdef public double min_x, max_x, a, b, c
def __init__(self, start, loop):
...