cython中def,cdef和cpdef的定义 [英] Definition of def, cdef and cpdef in cython
问题描述
我想知道 def
, cdef
和 cpdef
当我声明一个函数时。
def与其他之间的区别或多或少很明显。
而且我还看到有时在声明中添加返回类型( cdef void / double / int ... name
),有时没有。 / p>
我还想知道如何在cython中声明字符串变量,因为我不知道,我将其声明为对象。
def
在Python中声明一个函数。由于Cython基于C运行时,因此您可以使用 cdef
和 cpdef
。
cdef
在C语言层中声明函数。如您所知(或不?),您必须使用C语言定义每个函数的返回值类型。有时函数返回时会带有 void
,这与Python中的 return
相等。
Python是一种面向对象的语言。因此,您还可以在C ++语言层中定义类方法,并在子类中覆盖此方法:
cdef class A:
cdef foo(self):
打印 A
cdef class B(A)
cdef foo(self,x = None)
打印 B ,x
cdef类C(B):
cpdef foo(self,x = True,int k = 3)
打印 C,x,k
总结,为什么我们需要使用 def
, cdef
和 cpdef
?因为如果您使用Cython,则在编译之前,您的Python代码将被转换为C代码。因此,有了这些东西,您就可以控制生成的C代码清单。
有关更多信息,建议您阅读官方文档: http://docs.cython.org/src/reference/language_basics.html
I'd like to know the difference between def
, cdef
and cpdef
when I declare a function.
The difference between def and the others it's more or less clear.
And I've also seen that sometimes it's added the return type in the declaration (cdef void/double/int... name
) and sometimes not.
I'd also like to know how to declare a string variable in cython, as I didn't know it, I declared it as object.
def
declares a function in Python. Since Cython is based on C runtime, it allows you to use cdef
and cpdef
.
cdef
declares function in the layer of C language. As you know (or not?) in C language you have to define type of returning value for each function. Sometimes function returns with void
, and this is equal for just return
in Python.
Python is an object-oriented language. So you also can define class method in layer of C++ language, and override this methods in subclasses:
cdef class A:
cdef foo(self):
print "A"
cdef class B(A)
cdef foo(self, x=None)
print "B", x
cdef class C(B):
cpdef foo(self, x=True, int k=3)
print "C", x, k
Summary, why do we need to use def
, cdef
and cpdef
? Because if you use Cython, your Python code will be converted into C code before compile. So with this things you can control the resulting C-code listing.
For more information I suggest you to read the official documentation: http://docs.cython.org/src/reference/language_basics.html
这篇关于cython中def,cdef和cpdef的定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!