Python 源码学习(3):list 类型
Python 源码学习(3):list 类型 Python 中的 list 类型在源码中是一个名为 PyListObject 的结构体,定义在 listobject.h 文件中: // Include/cpython/listobject.h typedef struct { PyObject_VAR_HEAD /* Vector of pointers to list elements. list[0] is ob_item[0], etc. */ PyObject **ob_item; /* ob_item contains space for 'allocated' elements. The number * currently in use is ob_size. * Invariants: * 0 <= ob_size <= allocated * len(list) == ob_size * ob_item == NULL implies ob_size == allocated == 0 * list.sort() temporarily sets allocated to -1 to detect mutations. * * Items must normally not be NULL, except during construction when * the list is not yet visible outside the function that builds it. */ Py_ssize_t allocated; } PyListObject; 它的实现和 C++ 中的 std::vector 类似,都是通过维护一个动态数组,在增加数据的时候动态扩大数组的容量来实现的;PyListObject 结构中包含了一个变长对象头部 PyObject_VAR_HEAD,ob_size 表示当前动态数组的长度,**ob_item 是指向动态数组的指针,allocated 是动态数组的容量;我们可以从它的类型指针 PyTypeObject PyList_Type 中找到用来操作 list 对象的相关方法: ...