Python 导入cython函数:AttributeError:';模块';对象没有属性';乐趣';

Python 导入cython函数:AttributeError:';模块';对象没有属性';乐趣';,python,cython,Python,Cython,我已经写了一个小的cython代码 #t3.pyx from libc.stdlib cimport atoi cdef int fun(char *s): return atoi(s) setup.py文件是 from distutils.core import setup from Cython.Build import cythonize setup(ext_modules=cythonize("t3.pyx")) 我使用此命令运行setup.py python s

我已经写了一个小的
cython
代码

#t3.pyx
from libc.stdlib cimport atoi

cdef int fun(char *s):
        return atoi(s)
setup.py
文件是

from distutils.core import setup
from Cython.Build import cythonize

setup(ext_modules=cythonize("t3.pyx"))
我使用此命令运行
setup.py

python setup.py build_ext --inplace
这给了我

Compiling t3.pyx because it changed.
Cythonizing t3.pyx
running build_ext
building 't3' extension
x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-     prototypes -fno-strict-aliasing -D_FORTIFY_SOURCE=2 -g -fstack-protector-  strong -Wformat -Werror=format-security -fPIC -I/usr/include/python2.7 -c    t3.c -o build/temp.linux-x86_64-2.7/t3.o
t3.c:556:12: warning: ‘__pyx_f_2t3_fun’ defined but not used [-Wunused-function]
 static int __pyx_f_2t3_fun(char *__pyx_v_s) {
        ^
x86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security -Wl,-Bsymbolic-functions -Wl,-z,relro -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security build/temp.linux-x86_64-2.7/t3.o -o /home/debesh/Documents/cython/t3/t3.so
当我在
python
解释器中运行时,它会显示

>>> import t3
>>> t3.fun('1234')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'fun'
>>> 
导入t3 >>>t3.乐趣(“1234”) 回溯(最近一次呼叫最后一次): 文件“”,第1行,在 AttributeError:“模块”对象没有“乐趣”属性 >>>
这里的问题是您使用
cdef
而不是
def
定义了方法
cdef
方法只能从
cython
code调用

您可以在文档部分找到详细信息

Python函数是使用def语句定义的,就像在Python中一样。 它们将Python对象作为参数并返回Python对象

C函数是使用新的cdef语句定义的。他们两个都要 Python对象或C值作为参数,可以返回Python 对象或C值

重要的是:

在Cython模块中,Python函数和C函数可以分别调用它们 其他函数可以自由调用,但只能从外部调用Python函数 模块由解释的Python代码生成。那么,你想要什么函数 Cython模块的“导出”必须声明为Python函数 使用def


对于未来的读者,如果要在常规Python脚本中导入函数,您希望使用
cpdef
而不是
cdef
,那么您应该使用
def
,而不是
cpdef
。无论哪种方式,函数中的代码都会同时编译并以相同的速度运行
cpdef
仅在少数情况下有用,即您希望在Cython中调用性能关键循环中的函数,并且希望在Python中使用相同的函数。否则就是限制性的。