[Python源码学习]之数据类型

标准类型层次

根据Manual中The standard type hierarchy 一节的类型信息,我们首先尝试列出一个表:

类型

对象类

     

PyNone_Type

PyObject

None

   

PyBool_Type

PyLongObject

NotImplemented

   

PyEllipsis_Type

PyObject

Ellipsis

   

PyLone_Type

PyLongObject

numbers.Integral

numbers.Number

 

PyFloat_Type

 

numbers.Real

 

PyComplex_Type

 

numbers.Complex

 

PyUnicode_Type

PyUnicodeObject

Strings

Sequences

 

PyTuple_Type

 

Tuples

 

PyBytes_Type

PyBytesObject

Bytes

 

PyList_Type

 

Lists

 

PyByteArray_Type

 

Byte Arrays

 

PySet_Type

 

Sets

Set

 

PyTraceBack_Type

 

Frozen sets

 

PyDict_Type

 

Dictionaries

Mappings

 

PyFunction_Type

PyFunctionObject

用户自定义函数

Callable types

 

PyInstanceMethod_Type

PyInstanceMethodObject

实例的方法

 
 

生成器函数

 

PyCFunction_Type

PyCFunctionObject

内置函数

 
 

内置方法

 
 

 
 

类实例

 

PyModule_Type

 

Modules

   
 

Custom class

   
 

Class instances

   
 

I/O objects

   

PyCode_Type

 

Code objects

Internal types

 

PyFrame_Type

 

Frame objects

 

PyTraceBack_Type

 

Traceback objects

 

PySlice_Type

PySliceObject

Slice objects

 

PyStaticMethod_Type

staticmethod

Static method objects

 

PyClassMethod_Type

classmethod

Class 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'>

参考


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值