购买
下载掌阅APP,畅读海量书库
立即打开
畅读海量书库
扫码下载掌阅APP

0.3.5 类型对象

前面提到了PyObject的对象类型指针struct_typeobject*ob_type,它指向的对象类型决定了一个对象是什么类型。这是一个非常重要的结构体,不仅决定了对象的类型,还包含大量的元信息,包括创建对象需要分配多少内存,对象都支持哪些操作等。

现在了解一下struct_typeobject的源码,相关源码(Include/object.h)如下:


// Include/object.h
typedef struct _typeobject {
    PyObject_VAR_HEAD
    const char *tp_name; /* For printing, in format "<module>.<name>" */ // 类型名
    Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */
    // 创建该类型对象分配的内存空间大小

    // 一堆方法定义,函数和指针
    /* Methods to implement standard operations */
    destructor tp_dealloc;
    printfunc tp_print;
    getattrfunc tp_getattr;
    setattrfunc tp_setattr;
    PyAsyncMethods *tp_as_async; /* formerly known as tp_compare (Python 2)
                                    or tp_reserved (Python 3) */
    reprfunc tp_repr;

    /* Method suites for standard classes */
    // 标准类方法集
    PyNumberMethods *tp_as_number;      // 数值对象操作
    PySequenceMethods *tp_as_sequence;  // 序列对象操作
    PyMappingMethods *tp_as_mapping;    // 字典对象操作

    // 更多标准操作
    /* More standard operations (here for binary compatibility) */
    hashfunc tp_hash;
    ......

} PyTypeObject;

PyTypeObject的定义中包含许多信息,主要分为以下几类。

1)类型名tp_name,主要用于Python内部调试。

2)创建该类型对象时分配的空间大小信息,即tp_basicsize和tp_itemsize。

3)与该类型对象相关的操作信息,如tp_print这样的函数指针。

4)一些对象属性。 6XMIbaE6ECz9PQjhDHVrjT0ecvQndp71T6yn+lfX+h4pFGdutuGiJ4As5903oWDT

点击中间区域
呼出菜单
上一章
目录
下一章
×