问题描述
我对cython还很陌生,所以我有一个基本问题.我试图将基类从一个cython文件导入到另一个cython文件中,以定义派生类.我在名为cythonTest/
的单个目录中有以下代码:
I'm fairly new to cython, so I have a basic question. I'm trying to import a base class from one cython file into another cython file to define a derived class. I have the following code in a single directory called cythonTest/
:
afile.pxd
afile.pyx
bfile.pxd
bfile.pyx
__init__.py
setup.py
afile.pxd:
afile.pxd:
cdef class A:
pass
afile.pyx:
afile.pyx:
cdef class A:
def __init__(self):
print("A__init__()")
bfile.pxd:
bfile.pxd:
from afile cimport A
cdef class B(A):
pass
bfile.pyx:
bfile.pyx:
cdef class B(A):
def __init__(self):
print "B.__init__()"
setup.py:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
extensions = [Extension("afile", ["afile.pyx"]),
Extension("bfile", ["bfile.pyx"])]
setup(ext_modules=cythonize(extensions))
此代码似乎可以正确编译.运行import afile
可以正常工作,但是运行import bfile
会导致以下错误
This code seems to compile correctly. Running import afile
works fine, but running import bfile
results in the following error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "bfile.pyx", line 1, in init cythonTest.bfile
cdef class B(A):
ImportError: No module named cythonTest.afile
有人知道我在做什么错吗?我正在使用Python 2.7.6和Cython 0.27.3
Does anybody know what I'm doing wrong? I'm using Python 2.7.6 and Cython 0.27.3
推荐答案
您似乎正在使用cythonTest
作为程序包名称(包含__init__.py
的目录用作程序包).
You seem to be using cythonTest
as a package name (directory containing __init__.py
used as a package).
模块名称需要在扩展名中反映出来,以便导入才能正常工作:
The module name needs to be reflected in the extension names for importing to work correctly:
extensions = [Extension("cythonTest.afile", ["cythonTest/afile.pyx"]),
Extension("cythonTest.bfile", ["cythonTest/bfile.pyx"])]
可能还需要将pyx文件移动到软件包目录下-Cython在构建扩展名时使用软件包名称.
Will also probably need to move the pyx files under the package directory - Cython uses the package name when building the extensions.
这篇关于Cython中的ImportError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!