声明:本系列为本人阅读《python源码剖析》的读书笔记,如有侵权请及时告知本人openex@qq.com
1.PyObject
在python中一切都是对象,而所有的对象都有相同的部分,便是PyObject
通常情况下PyObject对象中存在两个成员:引用计数和对象类型
[object.h]
typedef struct _object {
PyObject_HEAD
} PyObject;
#ifdef Py_TRACE_REFS
/* Define pointers to support a doubly-linked list of all live heap objects. */
#define _PyObject_HEAD_EXTRA \
struct _object *_ob_next; \
struct _object *_ob_prev;
#define _PyObject_EXTRA_INIT 0, 0,
#else
#define _PyObject_HEAD_EXTRA
#define _PyObject_EXTRA_INIT
#endif
/* PyObject_HEAD defines the initial segment of every PyObject. */
#define PyObject_HEAD \
_PyObject_HEAD_EXTRA \
int ob_refcnt; \
struct _typeobject *ob_type;
实际发布时PyObject如下:
[object.h]
typedef struct _object {
int ob_refcnt; //引用计数
struct _typeobject *ob_type; //类型对象
} PyObject;
2.PyVarObject
例如字符串对象,不同的对象所需的内存空间可能不同,所以为了便于应对这种变长的对象,采用PyVarObject
[object.h]
#define PyObject_VAR_HEAD \
PyObject_HEAD \
int ob_size; //变长对象中容纳多少个元素,而不是字节的数量
typedef struct {
PyObject_VAR_HEAD
} PyVarObject;
3.PyTypeObject
类型对象中会保存该类型对象创建时所需空间大小,该类型所支持的函数(函数指针实现)
[object.h]
typedef struct _typeobject {
PyObject_VAR_HEAD
char *tp_name; /* For printing, in format "<module>.<name>" */
int tp_basicsize, tp_itemsize; /* For allocation */
/* Methods to implement standard operations */
destructor tp_dealloc;
printfunc tp_print;
……
/* More standard operations (here for binary compatibility) */
hashfunc tp_hash;
ternaryfunc tp_call;
……
} PyTypeObject;
4.PyType_Type
类型的类型,暂不描述
5.对象的多态性
python内部各函数之间传递的都是泛型指针PyObject*,进而通过ob_type域来实现多态性。
例如:
void Print(PyObject* object)
{
object->ob_type->tp_print(object);
}
6.简介引用计数
python中通过PyObject的ob_refcnt域来维护该对象的引用计数。
通常该对象增加引用时(如绑定到某变量),引用计数增加,变量删除时引用计数减少(del a)
当引用计数减为0时,会调用该对象对应类型的析构函数。
[object.h]
#define _Py_NewReference(op) ((op)->ob_refcnt = 1)
#define _Py_Dealloc(op) ((*(op)->ob_type->tp_dealloc)((PyObject *)(op)))
#define Py_INCREF(op) ((op)->ob_refcnt++)
#define Py_DECREF(op) \
if (--(op)->ob_refcnt != 0) \
; \
else \
_Py_Dealloc((PyObject *)(op))
/* Macros to use in case the object pointer may be NULL: */
#define Py_XINCREF(op) if ((op) == NULL) ; else Py_INCREF(op)
#define Py_XDECREF(op) if ((op) == NULL) ; else Py_DECREF(op)
7.Python对象的分类
- Internal: Python虚拟机内部运行时需要使用的对象
- Mapping: 关联对象
- Sequence:序列对象
- numeric: 数值对象
-
Fundamental对象:类型对象