閱讀361 返回首頁    go 阿裏雲 go 技術社區[雲棲]


[筆記]PyListObject對象

在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;

PyListObject是個可變對象,可以在運行時改變負責維護的內存,包括自身的長度和所包含元素的內容。
其中,成員ob_item指向存放元素的內存空間,allocated表示一共分配得到的可以存放元素的數目,
而頭部宏中包含的ob_size表示包含的有效元素的數目,因為PyListObject並不是要插入一個元素才申請一次空間的,而是一次性先申請一定數目的空間,即allocated。

需要考察第一次創建過程,以及當表滿了後,新增元素的處理。


JasonLee     2011.08.08     22:32     牙疼,犯困,早點休息



Python中使用PyList_New來創建新的PyListObject對象,在創建過程中會使用緩衝池的對象或者新建。
緩衝池的對象由不再使用的PyListObject構成,可以理解為“廢物利用”或者“環保重用”。
使用PyList_SetItem來設置PyListObject中某一元素的值。
使用PyList_Insert進行插入,實際上調用的ins1函數,過程會調用到list_resize函數調整大小,類似的還有listappend和listremove函數等。
插入、刪除等操作會涉及內存移動。


JasonLee     2011.08.10     23:54     今夜打籃球,早點休息

最後更新:2017-04-02 22:16:33

  上一篇:go [筆記]PyDictObject頭文件閱讀
  下一篇:go android中透明Dialog及ProgressDialog的實現