Cython class 属性错误

Cython class AttributeError

我已经开始尝试使用 Cython 和 运行 解决以下问题。考虑以下 class 表示 3D space 中的顶点:

#Vertex.pyx
cdef class Vertex(object):
    cdef double x, y, z
    def __init__(self, double x, double y, double z):        
        self.x = x
        self.y = y
        self.z = z

现在我尝试从 Python 控制台创建一个对象:

import Vertex as vt
v1 = vt.Vertex(0.0, 1.0, 0.0) 

效果很好。但是,当我尝试访问 class 属性时,我得到一个 AttributeError:

print v1.x
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-6-83d928d774b7> in <module>()
----> 1 print v1.x

AttributeError: 'Vertex.Vertex' object has no attribute 'x'

知道为什么会发生这种情况吗?

默认情况下 cdef 属性只能从 Cython 中访问。如果 you make it a public attributecdef public 在属性名称前面,那么 Cython 将生成合适的属性以便能够从 Python.

访问它

有关相关问题的一些额外说明:

如果您在 Cython 中遇到相同的错误,那么您可能忘记告诉 Cython 您的实例变量的类型(例如 v1)- Cython 本身可以愉快地访问 cdef 属性但它只有在知道类型的情况下才知道它们。如果它只是一个变量,那么 cdef 该变量。如果您尝试使用函数中的 return 值,或索引列表或类似内容,则可以使用强制转换:<Vectex>(func()).x仅当您确定类型时才执行此操作。

您可以使用 cdef 函数得到类似的错误,这些错误同样只在 Cython 中可见。在这种情况下,cpdef 使函数从 Cython 和 Python 可见。然而,cpdef 函数在某些方面是所有世界中最糟糕的(它们具有 cdef 函数的所有限制和 def 函数的所有限制) - 你通常最好选择一个仅限 Cython (cdef) 或 Python (def) 接口。