我开始尝试 Cython 并遇到以下问题。考虑以下表示 3D 空间中的顶点的类:#Vertex.pyxcdef 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 vtv1 = vt.Vertex(0.0, 1.0, 0.0) 这工作正常。但是,当我尝试访问类属性时,我得到了一个AttributeError:print v1.x---------------------------------------------------------------------------AttributeError Traceback (most recent call last)<ipython-input-6-83d928d774b7> in <module>()----> 1 print v1.xAttributeError: 'Vertex.Vertex' object has no attribute 'x'任何想法为什么会发生这种情况?
1 回答

繁星点点滴滴
TA贡献1803条经验 获得超3个赞
默认情况下,cdef
属性只能从 Cython 内部访问。如果您将其设置cdef public
为属性名称前面的公共属性,则 Cython 将生成合适的属性以便能够从 Python 访问它。
关于相关问题的一些额外说明:
如果您在 Cython 中遇到同样的错误,那么您可能忘记告诉 Cython 您的实例变量的类型(例如v1
)——Cython 本身可以愉快地访问cdef
属性,但它只有在知道类型时才知道它们。如果它只是一个变量,那么cdef
该变量。如果您尝试使用函数的返回值,或索引列表或类似内容,则可以使用 cast: <Vectex>(func()).x
。仅当您确定类型时才执行此操作。
您可能会遇到类似的cdef
函数错误,这些错误再次仅在 Cython 中可见。在这种情况下cpdef
,该函数对 Cython 和 Python 都可见。但是,cpdef
函数在某些方面是最糟糕的(它们具有cdef
函数的所有限制和def
函数的所有限制) - 通常最好选择 Cython-only ( cdef
) 或 Python ( def
) 接口。
添加回答
举报
0/150
提交
取消