考虑到性能的要求,我在工作中用的最多的是c/c++,然而,工作中又经常会有一些验证性的工作,这些工作对性能的要求并不高,反而对完成的效率要求更高,对于这样的工作,用一种开发效率高的语言是合理的想法,鉴于python的流行以及为大家所称道的开发效率和灵活性,我便开始渐渐多的接触起python来。可是,问题又来了,用python验证完了之后,需要优化性能,甚至移植到c/c++里面来,这时候,愈发觉得有必要深入学习python,了解其内部原理。经过一番搜索,找到了这本《Python源码剖析》,开始了我的python深入学习之旅。

一、Python对象初探

python语言中的一切,包括变量和变量类型,底层都是靠c语言的某种对象/结构体来实现的。也可以理解为,python中所有的东西都是用c的对象来实现的(这里理解为struct的对象)。这些所有对象都对应的定义中,开头的部分是相同的,都是PyObject:

[object.h]
typedef struct _object {
PyObject_HEAD
} PyObject;
[object.h]
#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;

整型变量ob_refcnt与Python的内存管理机制有关,它实现了基于引用计数的垃圾收集机制。而ob_type是一个指向_typeobject结构体的指针,_typeobject结构体定义了所指向对象的类型,定义如下:

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

也就是说PyTypeObject这个结构体定义了python的c代码中的对象的类型。

04-25 00:16
查看更多