Welcome 微信登录

首页 / 操作系统 / Linux / Python源码学习之数据类型

标准类型层次

根据Manual中The standard type hierarchy 一节的类型信息,我们首先尝试列出一个表:
类型对象类   
PyNone_TypePyObjectNone  
PyBool_TypePyLongObjectNotImplemented  
PyEllipsis_TypePyObjectEllipsis  
PyLone_TypePyLongObjectnumbers.Integralnumbers.Number 
PyFloat_Type numbers.Real 
PyComplex_Type numbers.Complex 
PyUnicode_TypePyUnicodeObjectStringsSequences 
PyTuple_Type Tuples 
PyBytes_TypePyBytesObjectBytes 
PyList_Type Lists 
PyByteArray_Type Byte Arrays 
PySet_Type SetsSet 
PyTraceBack_Type Frozen sets 
PyDict_Type DictionariesMappings 
PyFunction_TypePyFunctionObject用户自定义函数Callable types 
PyInstanceMethod_TypePyInstanceMethodObject实例的方法 
 生成器函数 
PyCFunction_TypePyCFunctionObject内置函数 
 内置方法 
  
 类实例 
PyModule_Type Modules  
 Custom class  
 Class instances  
 I/O objects  
PyCode_Type Code objectsInternal types 
PyFrame_Type Frame objects 
PyTraceBack_Type Traceback objects 
PySlice_TypePySliceObjectSlice objects 
PyStaticMethod_TypestaticmethodStatic method objects 
PyClassMethod_TypeclassmethodClass method objects 
刚开始接触这个东西,很多地方还不了解,以至于这个简单的表格都无法补全(留待以后慢慢完善)

Py***_Type

这些都是结构体 PyTypeObject 的实例,以 PyLong_Type 为例:
  • 变量声明在 Inlcude/longobject.h 中:
PyAPI_DATA(PyTypeObject) PyLong_Type;
  • 注:PyAPI_DATA是一个宏,定义在 Include/pyport.h 中,用来隐藏动态库时平台的差异,片段如下: ... #define PyAPI_FUNC(RTYPE) __declspec(dllexport) RTYPE #define PyAPI_DATA(RTYPE) extern __declspec(dllexport) RTYPE ...
  • 变量定义在 Object/longobject.c 中:
PyTypeObject PyLong_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "int", /* tp_name */ offsetof(PyLongObject, ob_digit), /* tp_basicsize */ sizeof(digit), /* tp_itemsize */ long_dealloc, /* tp_dealloc */ ... &long_as_number, /* tp_as_number */ ... long_new, /* tp_new */ PyObject_Del, /* tp_free */ };
  • PyTypeObject本身也是一个 PyObject,所以它也有自己的类型,这就是PyType_Type
PyTypeObject PyType_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "type", /* tp_name */ sizeof(PyHeapTypeObject), /* tp_basicsize */ sizeof(PyMemberDef), /* tp_itemsize */ (destructor)type_dealloc, /* tp_dealloc */ ...
  • 类型信息在Python中通过type来获取
>>> type(0L) <type "long"> >>> type(long) <type "type"> >>> type(type) <type "type">