ITPub博客

首页 > 应用开发 > Python > Python类型对象的结构

Python类型对象的结构

原创 Python 作者:raptors 时间:2025-11-12 16:19:28 0 删除 编辑

# Python类型对象的结构


在Python中,类型对象(type object)是用于定义其他对象行为的元类。所有类(包括内置类型和用户定义类)都是类型对象的实例。以下是Python类型对象的主要结构:


## CPython中的PyTypeObject


在CPython实现中,类型对象是通过`PyTypeObject`结构体定义的(位于`Include/cpython/object.h`):


```c

typedef struct _typeobject {

    PyObject_VAR_HEAD

    const char *tp_name; /* For printing, in format "<module>.<name>" */

    Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */

    

    /* Methods to implement standard operations */

    destructor tp_dealloc;

    Py_ssize_t tp_vectorcall_offset;

    getattrfunc tp_getattr;

    setattrfunc tp_setattr;

    PyAsyncMethods *tp_as_async;

    reprfunc tp_repr;

    

    /* Method suites for standard classes */

    PyNumberMethods *tp_as_number;

    PySequenceMethods *tp_as_sequence;

    PyMappingMethods *tp_as_mapping;

    

    /* More standard operations (here for binary compatibility) */

    hashfunc tp_hash;

    ternaryfunc tp_call;

    reprfunc tp_str;

    getattrofunc tp_getattro;

    setattrofunc tp_setattro;

    

    /* Functions to access object as input/output buffer */

    PyBufferProcs *tp_as_buffer;

    

    /* Flags to define presence of optional/expanded features */

    unsigned long tp_flags;

    

    const char *tp_doc; /* Documentation string */

    

    /* call function for all accessible objects */

    traverseproc tp_traverse;

    

    /* delete references to contained objects */

    inquiry tp_clear;

    

    /* rich comparisons */

    richcmpfunc tp_richcompare;

    

    /* weak reference enabler */

    Py_ssize_t tp_weaklistoffset;

    

    /* Iterators */

    getiterfunc tp_iter;

    iternextfunc tp_iternext;

    

    /* Attribute descriptor and subclassing stuff */

    struct PyMethodDef *tp_methods;

    struct PyMemberDef *tp_members;

    struct PyGetSetDef *tp_getset;

    struct _typeobject *tp_base;

    PyObject *tp_dict;

    descrgetfunc tp_descr_get;

    descrsetfunc tp_descr_set;

    Py_ssize_t tp_dictoffset;

    initproc tp_init;

    allocfunc tp_alloc;

    newfunc tp_new;

    freefunc tp_free; /* Low-level free-memory routine */

    inquiry tp_is_gc; /* For PyObject_IS_GC */

    PyObject *tp_bases;

    PyObject *tp_mro; /* method resolution order */

    PyObject *tp_cache;

    PyObject *tp_subclasses;

    PyObject *tp_weaklist;

    destructor tp_del;

    

    /* Type attribute cache version tag. Added in version 2.6 */

    unsigned int tp_version_tag;

    

    destructor tp_finalize;

    vectorcallfunc tp_vectorcall;

} PyTypeObject;

```


## 主要组成部分


1. **基本对象信息**:

   - `PyObject_VAR_HEAD`:包含引用计数和类型信息

   - `tp_name`:类型名称(如"int"、"str"或"module.class")


2. **内存管理**:

   - `tp_basicsize`, `tp_itemsize`:对象内存分配大小

   - `tp_alloc`, `tp_free`, `tp_dealloc`:分配/释放函数


3. **操作方法集**:

   - `tp_as_number`:数值操作(加减乘除等)

   - `tp_as_sequence`:序列操作(获取长度、索引等)

   - `tp_as_mapping`:映射操作(键值访问等)

   - `tp_as_buffer`:缓冲区协议支持


4. **特殊方法**:

   - `tp_init`:`__init__`方法

   - `tp_new`:`__new__`方法

   - `tp_repr`, `tp_str`:`__repr__`和`__str__`

   - `tp_hash`:`__hash__`

   - `tp_call`:使实例可调用


5. **面向对象特性**:

   - `tp_base`:基类

   - `tp_bases`:基类元组

   - `tp_mro`:方法解析顺序

   - `tp_dict`:类命名空间字典

   - `tp_getset`:属性描述符

   - `tp_methods`:方法定义


6. **其他特性**:

   - `tp_flags`:类型标志位

   - `tp_doc`:文档字符串

   - `tp_weaklistoffset`:弱引用支持

   - `tp_subclasses`:子类列表


## Python中的表现


在Python层面,类型对象表现为`type`类的实例:


```python

>>> int.__class__

https://zq.zhaopin.com/moment/71132481

https://zq.zhaopin.com/moment/71132410

https://zq.zhaopin.com/moment/71132324

https://zq.zhaopin.com/moment/71132266

https://zq.zhaopin.com/moment/71132182

https://zq.zhaopin.com/moment/71132146

https://zq.zhaopin.com/moment/71132113

https://zq.zhaopin.com/moment/71131967

https://zq.zhaopin.com/moment/71131647

https://zq.zhaopin.com/moment/71131574

https://zq.zhaopin.com/moment/71131461

https://zq.zhaopin.com/moment/71131402

https://zq.zhaopin.com/moment/71131227

https://zq.zhaopin.com/moment/71131153

https://zq.zhaopin.com/moment/71131096

https://zq.zhaopin.com/moment/71130881

https://zq.zhaopin.com/moment/71130617



<class 'type'>

>>> class A: pass

>>> A.__class__

<class 'type'>

```


可以通过`dir()`查看类型对象的属性和方法:


```python

>>> dir(type)

['__abstractmethods__', '__base__', '__bases__', '__basicsize__', '__call__', ...]

```


类型对象定义了类的行为,包括实例化、属性访问、方法调用等所有操作。理解类型对象的结构对于深入理解Python的对象模型和元编程非常重要。


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/34366/viewspace-3101104/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-09-29

  • 博文量
    20
  • 访问量
    20448