【发布时间】:2017-02-10 23:51:02
【问题描述】:
我正在尝试这个 url 上的示例。 http://cython.readthedocs.io/en/latest/src/userguide/buffer.html
为了测试它,我执行以下操作。
import pyximport
pyximport.install(build_dir = 'build')
import ctest
m = ctest.Matrix(10)
m.add_row()
print(m)
当我调用 m.add_row() 函数说时,这给了我一个错误
TypeError: 'int' object is not iterable
在类中add_row被定义为
from cpython cimport Py_buffer
from libcpp.vector cimport vector
cdef class Matrix:
cdef Py_ssize_t ncols
cdef Py_ssize_t shape[2]
cdef Py_ssize_t strides[2]
cdef vector[float] v
def __cinit__(self, Py_ssize_t ncols):
self.ncols = ncols
def add_row(self):
"""Adds a row, initially zero-filled."""
self.v.extend(self.ncols)
...
假设在 cython 中对向量调用 extend 与在 python 列表上扩展完全相同,这个错误对我来说完全有意义。您没有传递一个数字,而是一个附加到列表的可迭代对象。
我可以通过这样做来解决它...
def add_row(self):
"""Adds a row, initially zero-filled."""
self.v.extend([0] * self.ncols)
我只是想知道示例中是否有错字,或者我是否遗漏了什么。向量的扩展函数来自哪里?在与 cython 一起分发的 vector.pxd 文件中,它从不导入扩展函数,甚至在 c++ 标准库中也不存在。 cython 对向量类型有什么特别的作用吗?
https://github.com/cython/cython/blob/master/Cython/Includes/libcpp/vector.pxd
【问题讨论】: