迭代器协议 — Python 文档
来自菜鸟教程
Python/docs/3.6/c-api/iter
有两个函数专门用于处理迭代器。
要编写一个遍历迭代器的循环,C 代码应如下所示:
PyObject *iterator = PyObject_GetIter(obj);
PyObject *item;
if (iterator == NULL) {
/* propagate error */
}
while (item = PyIter_Next(iterator)) {
/* do something with item */
...
/* release reference when done */
Py_DECREF(item);
}
Py_DECREF(iterator);
if (PyErr_Occurred()) {
/* propagate error */
}
else {
/* continue doing useful work */
}