跟着《Python源码剖析》,一方面学习python,另一方面学习C。
简单记录,以框架为主,以防忘记。
------------------------------------------------------------------------------------------
1、Python一切为对象,内置类型,自建类,函数,模块,甚至运行时环境……
2、一切对象都含有的基础对象:
其实以 #define PyObject_HEAD …… 定义而出
typedef struct _object {
int ob_refcnt; // 引用计数
struct _typeobject *ob_type; // 类型指针
} PyObject;
变长对象
其实以 #define PyObject_VAR_HEAD …… 定义而出
typedef struct _object {
int ob_refcnt;
struct _typeobject *ob_type;
int ob_size; // 对象大小
} PyObject;
对象的类型 -- ob_type指针所指向的
typedef struct _typeobject {
PyObject_VAR_HEAD
const char *tp_name; // 存储类型名
……
hashfunc tp_hash; // hash函数指针
……
} PyTypeObject;
3、对象与对象的类型
整数对象可定义如下
typedef struct _intobject {
PyObject_HEAD
long ival; // 存储的实际值
} PyIntObject;
通过上述结构体可定义出如下实体
PyTypeObject PyType_Tpye; // 类型的类型
PyTypeObject PyInt_Tpye; // 整数的类型
PyIntObject Int_A; // 一个整数对象
相互关系如下
使Int_A的ob_type指向PyInt_Type,便可实现面向对象的功能。Int_A.ob_type.tp_hash可以调用Int的hash函数。同样的,若是String_A的ob_type指向PyString_Type,
String_A.ob_type.tp_hash可调用String的hash函数,也就实现了多态。
由于PyInt_Type也是一种对象,令其ob_type指向PyType_Type,PyType_Type的ob_type指向自身。