【问题标题】: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?Cython:一个类需要有一个 Cython 扩展类型的 python 列表作为其属性——因此,这个类本身不能是扩展类型吗?
【发布时间】:2015-03-09 17:36:06
【问题描述】:

假设我有一个名为 Point 的 Cython 扩展类型。

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

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

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

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

我理解正确吗?

【问题讨论】:

    标签: python design-patterns cython


    【解决方案1】:

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

    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 的文档,properties 部分的第二个示例还提供了扩展类型如何包装列表而不提供直接访问的示例。

    【讨论】:

      【解决方案2】:

      我不知道 Cython 扩展类型有任何此类限制。但是,从standard documentation on general extension types 来看,很明显您可以创建任意的PyObjects 作为扩展类型中的成员变量(参见the Noddy2 example 和无限制的PyObject 成员firstlast,它们后来被细化为受限到字符串类型)。如果您走这条路,您可以将成员公开为PyObject,并按照惯例将list 传递给它,或者将其完全限制为list

      【讨论】:

      • Cython 扩展类型可能与 Python 扩展类型不同?
      • 这几乎可以肯定,但在这种情况下,我怀疑坚持标准文档中描述的方法会更好如果您需要这样的内置属性。跨度>
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-14
      • 2021-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多