10

我将 Python 类转换为 .pyx 文件中的扩展类型。我可以在另一个 Cython 模块中创建这个对象,但我不能用它做静态类型。

这是我的课的一部分:

cdef class PatternTree:

    cdef public PatternTree previous
    cdef public PatternTree next
    cdef public PatternTree parent
    cdef public list children

    cdef public int type
    cdef public unicode name
    cdef public dict attributes
    cdef public list categories
    cdef public unicode output

    def __init__(self, name, parent=None, nodeType=XML):
        # Some code

    cpdef int isExpressions(self):
        # Some code

    cpdef MatchResult isMatch(self, PatternTree other):
        # Some code

    # More functions...

我曾尝试使用 .pxd 文件来声明它,但它在我的所有函数上都显示“C 方法 [某些函数] 已声明但未定义”。我还尝试在我的实现的函数中剥离 C 的东西,使它像一个增强的类,但这也不起作用。

这是我的.pxd:

cdef class PatternTree:
    cdef public PatternTree previous
    cdef public PatternTree next
    cdef public PatternTree parent
    cdef public list children

    cdef public int type
    cdef public unicode name
    cdef public dict attributes
    cdef public list categories
    cdef public unicode output

    # Functions
    cpdef int isExpressions(self)
    cpdef MatchResult isMatch(self, PatternTree other)

谢谢你的帮助!

4

1 回答 1

12

我找到了解决办法。这是解决方案:

在 .pyx 中:

cdef class PatternTree:

    # NO ATTRIBUTE DECLARATIONS!

    def __init__(self, name, parent=None, nodeType=XML):
        # Some code

    cpdef int isExpressions(self):
        # Some code

    cpdef MatchResult isMatch(self, PatternTree other):
        # More code

在 .pxd 中:

cdef class PatternTree:
    cdef public PatternTree previous
    cdef public PatternTree next
    cdef public PatternTree parent
    cdef public list children

    cdef public int type
    cdef public unicode name
    cdef public dict attributes
    cdef public list categories
    cdef public unicode output

    # Functions
    cpdef int isExpressions(self)
    cpdef MatchResult isMatch(self, PatternTree other)

在任何 Cython 模块(.pyx)中,我想将其用于:

cimport pattern_tree
from pattern_tree cimport PatternTree

最后一句警告:Cython不支持相对导入。这意味着您必须提供相对于您正在执行的主文件的整个模块路径。

希望这可以帮助那里的人。

于 2013-07-19T20:34:24.627 回答