我尝试根据我正在研究的项目为Python创建一个修改过的列表类,并决定尝试使用Cython加速它
在我第一次使用时,大多数课程的功能(特殊功能除外)都不可见,无法访问
我试图从cdef,cpdef和def的名称中反复出现方法和类声明,并尝试使用Google搜索以查看我是否拥有正确的语法以及是否有其他人拥有类似的问题
这是我的代码:
class list_2:
cpdef append(self , object item):
self._lst = array(self + [item])
cpdef pop(self,int index = -1):
temp_lst = array(range(len(self) -1 ))
if index > len(self)-1 and index >= 0 or index*(-1) > len(len) and index < 0:
raise IndexError
else:
if index <0:
index = index*(-1)-1
for x in range(len(self)):
if x!= index:
temp_lst[i] = self[x]
i+=1
self._lst = temp_lst
答案 0 :(得分:0)
这是一个帮助您开始使用cython类的简单示例。首先,我创建了我的setup.py
文件,我通过调用.pyx
来编译我的cython python setup.py build_ext --inplace
文件。
from distutils.core import setup
from Cython.Build import cythonize
from distutils.core import Extension
extensions = [
Extension("mylist", sources=["mylist.pyx"], libraries=[], extra_compile_args=["-w"]),
]
setup(
ext_modules = cythonize(extensions)
)
接下来,我会写一个.pxd
文件。就像我在评论中提到的那样,这基本上是一个头文件,它定义了您要访问的所有“c-side”类属性和方法,这些属性和方法是使用cdef
或cpdef
定义的。示例mylist.pxd
如下所示:
cdef class MyList:
cdef public list _base_list
cpdef append(self, object item)
cpdef pop(self, int index=*)#Note: * is used in place of default values
cpdef get_data(self)
现在我们已准备好创建实际完成工作的mylist.pyx
文件。为了简单起见,我将使用python列表实现我们的cython列表(这在性能上是非常荒谬的,但是将避免需要深入研究数组,这有点棘手)。代码可能如下所示:
cdef class MyList:
def __cinit__(self):#__cinit__ is preferred for cdef class constructors
self._base_list = []
cpdef append(self, object item):
self._base_list = self._base_list + [item]
cpdef pop(self, int index=-1):
self._base_list.pop(index)
cpdef get_data(self):
return self._base_list
一旦编译完毕,你就可以在python中使用这个愚蠢的MyList
类。以下是MyList
文件中的main.py
:
from mylist import MyList
a = MyList()
a.append("apple")
a.append("banana")
a.append("tomato")
a.append("pear")
a.pop(2)#one of these fruit is not like the others...
print a.get_data()
如果您在编译或运行此示例时遇到问题,请与我们联系。我使用Python 2.7和最新的Cython master(版本0.26b0)在笔记本电脑上测试了这个。