Cython:一个 class 需要有一个 python Cython 扩展类型列表作为它的属性——因此,这个 class 本身不能是一个扩展类型?

Cython: a class needs to have as its attribute a python list of Cython extension types -- thus, this class cannot be an extension type itself?

假设我有一个名为 Point.

的 Cython 扩展类型

然后,我需要创建一个名为 Points 的 class,它的属性之一是包含 Point 个对象的 Python 列表。现在,据我所知,Python 列表不能是扩展类型的属性,因为只有 C 数据类型可以。

我想使用 Python 列表来保存 Cython 扩展类型的列表,因为我听说这是最简单的方法,并且通过 Cython 访问 Python 列表是退出的高效。

因此,Points 必须是正常的 Python/Cython class,而不是扩展类型,对吗?这样,我可以执行以下操作:

def class Points:
    def __init__(self, num_points):
        self.points = [Point() for x in range(num_points)]

我理解正确吗?

我不知道 Cython 扩展类型有任何此类限制。但是,来自具有不受限制的 PyObject 成员 firstlaststandard documentation on general extension types, it's clear you can create arbitrary PyObjects as member variables in an extension type (see the Noddy2 example,它们后来被细化为仅限于字符串类型)。如果你走这条路,你可以将成员公开为 PyObject 并按照惯例将其传递为 list 或将其完全限制为 list.

不,没有这样的限制,Cython 扩展类型可以有任意 Python 个对象作为属性。例如,您可以通过以下方式声明您的 Points class:

cdef class Points:
    cdef list points
    def __init__(self, num_points):
        self.points = [Point() for x in range(num_points)]

注意需要提前声明Cython扩展类型的所有属性。如果您不想将属性限制为特定的 Python 对象,您也可以使用 object 而不是 list。如果你想将你的 points 属性暴露给 Python,即允许从 Python 直接访问,你需要将其声明为 public(即 cdef public list points)。

查看有关 attributes of extension types for more details and the second example of the properties 部分的文档还提供了扩展类型如何在不提供直接访问的情况下包装列表的示例。