Yikun / yikun.github.com

Yikun's Blog
69 stars 22 forks source link

Python3源码学习-对象 #36

Open Yikun opened 8 years ago

Yikun commented 8 years ago

最近开始看Python源码,大致看了看,发现Py2和Py3的部分实现差别挺大,《Python源码剖析》是根据Python 2写的。不过为了能激发主动性,便直接从Python 3(3.5.0)源码看起了,然后也会结合Python 2(2.7.10)的代码看看之前的实现,来对比学习~:)

1. 万物皆对象

在Python中,万物皆对象,那么对象又是什么结构,如何组织,怎样实现的呢?

Objects are structures allocated on the heap. Special rules apply to the use of objects to ensure they are properly garbage-collected. Objects are never allocated statically or on the stack; they must be accessed through special macros and functions only.(Type objects are exceptions to the first rule; the standard types are represented by statically initialized type objects, although work on type/class unification for Python 2.2 made it possible to have heap-allocated type objects too).

从Python的源码注释可以得到以下信息点:

然后,还补充说,Type对象除外,标准的type对象是静态初始化的,Python 2.2把在堆上初始化type对象变成了现实。

2. 对象的结构

object

Python中的对象,主要分为一般对象和变长对象(list、dict之类),一般的对象就是PyObject,然后变长对象其实就是给PyObject加了个size成为了PyVarObject。

对于所有对象来说,均有2个重要的元素:

对于可变长的对象(比如list,dict),会多一个域:

另外头部还有_PyObject_HEAD_EXTRA,这个宏定义了next和prev指针,用来支持用一个双链表把所有堆中的对象串起来。

/* 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;

参考资料

Python-3.5.0源码 PYTHON 源码阅读 - 对象 Python源码剖析