TOC

Python 源码学习 06: <code>tuple</code>

源码

INIT_TYPE(&PyTuple_Type, "tuple");
SETBUILTIN("tuple", &PyTuple_Type);

**cpython/Include/cpython/tupleobject.h**

typedef struct {
    PyObject_VAR_HEAD
    /* ob_item contains space for 'ob_size' elements.
       Items must normally not be NULL, except during construction when
       the tuple is not yet visible outside the function that builds it. */
    PyObject *ob_item[1];
} PyTupleObject;

当然,与之对应的 PyTypeObject PyTuple_Type 定义在 Objects/tupleobject.c,就不贴出来了。

PyTuple_SET_ITEM 似乎是在完成内存初始化的空间内填充元素时使用的。

成员方法

tuple 类型只有两个成员方法:count, index

#define TUPLE_INDEX_METHODDEF    \
    {"index", (PyCFunction)(void(*)(void))tuple_index, METH_FASTCALL, tuple_index__doc__},

#define TUPLE_COUNT_METHODDEF    \
    {"count", (PyCFunction)tuple_count, METH_O, tuple_count__doc__},

static PyMethodDef tuple_methods[] = {
    TUPLE___GETNEWARGS___METHODDEF
    TUPLE_INDEX_METHODDEF
    TUPLE_COUNT_METHODDEF
    {"__class_getitem__", (PyCFunction)Py_GenericAlias, METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
    {NULL,              NULL}           /* sentinel */
};

引用计数

Py_INCREF
Py_DECREF
Py_XINCREF
Py_XDECREF