类型对象

也许 Python 对象系统中最重要的结构之一就是定义新类型的结构: PyTypeObject 结构。 类型对象可以使用任何 PyObject_*()PyType_*() 函数来处理,但不能提供大多数 Python 应用程序所感兴趣的内容。 这些对象是对象行为的基础,所以它们对解释器本身或任何实现新类型的扩展模块都非常重要。

与大多数标准类型相比,类型对象相当大。这么大的原因是每个类型对象存储了大量的值,大部分是C函数指针,每个指针实现了类型功能的一小部分。本节将详细描述类型对象的字段。这些字段将按照它们在结构中出现的顺序进行描述。

除了下面的快速参考, 例子 小节提供了快速了解 PyTypeObject 的含义和用法的例子。

快速参考

"tp_方法槽"

PyTypeObject 槽 1

Type

特殊方法/属性

信息 2

O

T

D

I

<R> tp_name

const char *

__name__

X

X

tp_basicsize

Py_ssize_t

X

X

X

tp_itemsize

Py_ssize_t

X

X

tp_dealloc

destructor

X

X

X

tp_vectorcall_offset

Py_ssize_t

X

X

(tp_getattr)

getattrfunc

__getattribute__, __getattr__

G

(tp_setattr)

setattrfunc

__setattr__, __delattr__

G

tp_as_async

PyAsyncMethods *

子方法槽(方法域)

%

tp_repr

reprfunc

__repr__

X

X

X

tp_as_number

PyNumberMethods *

子方法槽(方法域)

%

tp_as_sequence

PySequenceMethods *

子方法槽(方法域)

%

tp_as_mapping

PyMappingMethods *

子方法槽(方法域)

%

tp_hash

hashfunc

__hash__

X

G

tp_call

ternaryfunc

__call__

X

X

tp_str

reprfunc

__str__

X

X

tp_getattro

getattrofunc

__getattribute__, __getattr__

X

X

G

tp_setattro

setattrofunc

__setattr__, __delattr__

X

X

G

tp_as_buffer

PyBufferProcs *

%

tp_flags

unsigned long

X

X

?

tp_doc

const char *

__doc__

X

X

tp_traverse

traverseproc

X

G

tp_clear

inquiry

X

G

tp_richcompare

richcmpfunc

__lt__, __le__, __eq__, __ne__, __gt__, __ge__

X

G

tp_weaklistoffset

Py_ssize_t

X

?

tp_iter

getiterfunc

__iter__

X

tp_iternext

iternextfunc

__next__

X

tp_methods

PyMethodDef []

X

X

tp_members

PyMemberDef []

X

tp_getset

PyGetSetDef []

X

X

tp_base

PyTypeObject *

__base__

X

tp_dict

PyObject *

__dict__

?

tp_descr_get

descrgetfunc

__get__

X

tp_descr_set

descrsetfunc

__set__, __delete__

X

tp_dictoffset

Py_ssize_t

X

?

tp_init

initproc

__init__

X

X

X

tp_alloc

allocfunc

X

?

?

tp_new

newfunc

__new__

X

X

?

?

tp_free

freefunc

X

X

?

?

tp_is_gc

inquiry

X

X

<tp_bases>

PyObject *

__bases__

~

<tp_mro>

PyObject *

__mro__

~

[tp_cache]

PyObject *

[tp_subclasses]

PyObject *

__subclasses__

[tp_weaklist]

PyObject *

(tp_del)

destructor

[tp_version_tag]

unsigned int

tp_finalize

destructor

__del__

X

tp_vectorcall

vectorcallfunc

1

小括号中的槽名表示它(实际上)已弃用。尖括号中的名称应该被视为只读的。方括号中的名称仅供内部使用。"<R>"(作为前缀)表示该字段是必需的(必须是非null)。

2

列:

"O": PyBaseObject_Type 必须设置

"T": PyType_Type 必须设置

"D": 默认设置(如果方法槽被设置为NULL)

X - PyType_Ready sets this value if it is NULL
~ - PyType_Ready always sets this value (it should be NULL)
? - PyType_Ready may set this value depending on other slots

Also see the inheritance column ("I").

"I": 继承

X - type slot is inherited via *PyType_Ready* if defined with a *NULL* value
% - the slots of the sub-struct are inherited individually
G - inherited, but only in combination with other slots; see the slot's description
? - it's complicated; see the slot's description

注意,有些方法槽是通过普通属性查找链有效继承的。

子方法槽(方法域)

方法槽

Type

特殊方法

am_await

unaryfunc

__await__

am_aiter

unaryfunc

__aiter__

am_anext

unaryfunc

__anext__

nb_add

binaryfunc

__add__ __radd__

nb_inplace_add

binaryfunc

__iadd__

nb_subtract

binaryfunc

__sub__ __rsub__

nb_inplace_subtract

binaryfunc

__isub__

nb_multiply

binaryfunc

__mul__ __rmul__

nb_inplace_multiply

binaryfunc

__imul__

nb_remainder

binaryfunc

__mod__ __rmod__

nb_inplace_remainder

binaryfunc

__imod__

nb_divmod

binaryfunc

__divmod__ __rdivmod__

nb_power

ternaryfunc

__pow__ __rpow__

nb_inplace_power

ternaryfunc

__ipow__

nb_negative

unaryfunc

__neg__

nb_positive

unaryfunc

__pos__

nb_absolute

unaryfunc

__abs__

nb_bool

inquiry

__bool__

nb_invert

unaryfunc

__invert__

nb_lshift

binaryfunc

__lshift__ __rlshift__

nb_inplace_lshift

binaryfunc

__ilshift__

nb_rshift

binaryfunc

__rshift__ __rrshift__

nb_inplace_rshift

binaryfunc

__irshift__

nb_and

binaryfunc

__and__ __rand__

nb_inplace_and

binaryfunc

__iand__

nb_xor

binaryfunc

__xor__ __rxor__

nb_inplace_xor

binaryfunc

__ixor__

nb_or

binaryfunc

__or__ __ror__

nb_inplace_or

binaryfunc

__ior__

nb_int

unaryfunc

__int__

nb_reserved

void *

nb_float

unaryfunc

__float__

nb_floor_divide

binaryfunc

__floordiv__

nb_inplace_floor_divide

binaryfunc

__ifloordiv__

nb_true_divide

binaryfunc

__truediv__

nb_inplace_true_divide

binaryfunc

__itruediv__

nb_index

unaryfunc

__index__

nb_matrix_multiply

binaryfunc

__matmul__ __rmatmul__

nb_inplace_matrix_multiply

binaryfunc

__imatmul__

mp_length

lenfunc

__len__

mp_subscript

binaryfunc

__getitem__

mp_ass_subscript

objobjargproc

__setitem__, __delitem__

sq_length

lenfunc

__len__

sq_concat

binaryfunc

__add__

sq_repeat

ssizeargfunc

__mul__

sq_item

ssizeargfunc

__getitem__

sq_ass_item

ssizeobjargproc

__setitem__ __delitem__

sq_contains

objobjproc

__contains__

sq_inplace_concat

binaryfunc

__iadd__

sq_inplace_repeat

ssizeargfunc

__imul__

bf_getbuffer

getbufferproc()

bf_releasebuffer

releasebufferproc()

槽位 typedef

typedef

参数类型

返回类型

allocfunc

PyObject *

destructor

void *

void

freefunc

void *

void

traverseproc

void *
void *

int

newfunc

PyObject *

initproc

int

reprfunc

PyObject *

PyObject *

getattrfunc

const char *

PyObject *

setattrfunc

const char *

int

getattrofunc

PyObject *

setattrofunc

int

descrgetfunc

PyObject *

descrsetfunc

int

hashfunc

PyObject *

Py_hash_t

richcmpfunc

int

PyObject *

getiterfunc

PyObject *

PyObject *

iternextfunc

PyObject *

PyObject *

lenfunc

PyObject *

Py_ssize_t

getbufferproc

int

releasebufferproc

void

inquiry

void *

int

unaryfunc

PyObject *

binaryfunc

PyObject *

ternaryfunc

PyObject *

ssizeargfunc

PyObject *

ssizeobjargproc

int

objobjproc

int

objobjargproc

int

请参阅 槽位类型 typedef 里有更多详细信息。

PyTypeObject 定义

PyTypeObject 的结构定义可以在 Include/object.h 中找到。 为了方便参考,此处复述了其中的定义:

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; /* formerly known as tp_compare (Python 2)
                                    or tp_reserved (Python 3) */
    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;

} PyTypeObject;

PyObject 槽位

类型对象结构扩展了 PyVarObject 结构。 ob_size 字段用于动态类型 (由 type_new() 创建,通常通过 类 语句来调用)。 注意 PyType_Type (元类型) 会初始化 tp_itemsize,这意味着它的实例 (即类型对象) 必须 具有 ob_size 字段。

PyObject* PyObject._ob_next
PyObject* PyObject._ob_prev

These fields are only present when the macro Py_TRACE_REFS is defined. Their initialization to NULL is taken care of by the PyObject_HEAD_INIT macro. For statically allocated objects, these fields always remain NULL. For dynamically allocated objects, these two fields are used to link the object into a doubly-linked list of all live objects on the heap. This could be used for various debugging purposes; currently the only use is to print the objects that are still alive at the end of a run when the environment variable PYTHONDUMPREFS is set.

继承:

这些字段不会被子类型继承。

Py_ssize_t PyObject.ob_refcnt

这是类型对象的引用计数,由 PyObject_HEAD_INIT 宏初始化为 1。 请注意对于静态分配的类型对象 (对象的 ob_type 指回该类型) 不会 被加入引用计数。 但对于动态分配的类型对象,实例 确实 会被算作引用。

继承:

子类型不继承此字段。

PyTypeObject* PyObject.ob_type

这是类型的类型,换句话说就是元类型,它由宏 PyObject_HEAD_INIT 的参数来做初始化,它的值一般情况下是 &PyType_Type 。可是为了使动态可载入扩展模块至少在Windows上可用,编译器会报错这是一个不可用的初始化。因此按照惯例传递 NULL 给宏 PyObject_HEAD_INIT 并且在模块的初始化函数开始时候其他任何操作之前初始化这个字段。典型做法是这样的:

Foo_Type.ob_type = &PyType_Type;

这应该在创建该类型的任何实例之前完成。PyType_Ready() 检查 ob_type 是否为 NULL,如果是,则用基类的 ob_type 字段初始化它。如果该字段非零,则 PyType_Ready() 不会更改它。

继承:

此字段会被子类型继承。

PyVarObject 槽位

Py_ssize_t PyVarObject.ob_size

For statically allocated type objects, this should be initialized to zero. For dynamically allocated type objects, this field has a special internal meaning.

继承:

子类型不继承此字段。

PyTypeObject 槽

每个槽位都有一个部分来描述继承关系。如果 PyType_Ready() 会在该字段为 NULL 时设置它的值,那么也会有一个“默认”部分。(注意,在 PyBaseObject_TypePyType_Type 中设置的许多字段实际上就是默认值。)

const char* PyTypeObject.tp_name

指针,指向以 NULL 结尾的表示类型名称的字符串。对于可以作为模块的全局变量访问的类型,字符串应该是完整的模块名,后跟一个点,再后跟类型名。对于内置类型,字符串应该只是类型名。如果模块是包的子模块,则完整的包名是完整的模块名的一部分。例如,包 P 的子包 Q 的模块 M 中定义的类型 Ttp_name 应该初始化为 "P.Q.M.T"

For dynamically allocated type objects, this should just be the type name, and the module name explicitly stored in the type dict as the value for key '__module__'.

For statically allocated type objects, the tp_name field should contain a dot. Everything before the last dot is made accessible as the __module__ attribute, and everything after the last dot is made accessible as the __name__ attribute.

如果不存在点号,则整个 tp_name 字段将作为 __name__ 属性访问,而 __module__ 属性则将是未定义的(除非在字典中显式地设置,如上文所述)。 这意味着你的类型将无法执行 pickle。 此外,用 pydoc 创建的模块文档中也不会列出该类型。

该字段不可为 NULL。 它是 PyTypeObject() 中唯一的必填字段(除了潜在的 tp_itemsize 以外)。

继承:

子类型不继承此字段。

Py_ssize_t PyTypeObject.tp_basicsize
Py_ssize_t PyTypeObject.tp_itemsize

通过这些字段可以计算出该类型实例以字节为单位的大小。

存在两种类型:具有固定长度实例的类型其 tp_itemsize 字段为零;具有可变长度实例的类型其 tp_itemsize 字段不为零。 对于具有固定长度实例的类型,所有实例的大小都相同,具体大小由 tp_basicsize 给出。

For a type with variable-length instances, the instances must have an ob_size field, and the instance size is tp_basicsize plus N times tp_itemsize, where N is the "length" of the object. The value of N is typically stored in the instance's ob_size field. There are exceptions: for example, ints use a negative ob_size to indicate a negative number, and N is abs(ob_size) there. Also, the presence of an ob_size field in the instance layout doesn't mean that the instance structure is variable-length (for example, the structure for the list type has fixed-length instances, yet those instances have a meaningful ob_size field).

The basic size includes the fields in the instance declared by the macro PyObject_HEAD or PyObject_VAR_HEAD (whichever is used to declare the instance struct) and this in turn includes the _ob_prev and _ob_next fields if they are present. This means that the only correct way to get an initializer for the tp_basicsize is to use the sizeof operator on the struct used to declare the instance layout. The basic size does not include the GC header size.

关于对齐的说明:如果变量条目需要特定的对齐,则应通过 tp_basicsize 的值来处理。 例如:假设某个类型实现了一个 double 数组。 tp_itemsize 就是 sizeof(double)。 程序员有责任确保 tp_basicsizesizeof(double) 的倍数(假设这是 double 的对齐要求)。

对于任何具有可变长度实例的类型,该字段不可为 NULL

继承:

这些字段将由子类分别继承。 如果基本类型有一个非零的 tp_itemsize,那么在子类型中将 tp_itemsize 设置为不同的非零值通常是不安全的(不过这取决于该基本类型的具体实现)。

destructor PyTypeObject.tp_dealloc

指向实例析构函数的指针。除非保证类型的实例永远不会被释放(就像单例对象 NoneEllipsis 那样),否则必须定义这个函数。函数声明如下:

void tp_dealloc(PyObject *self);

当引用计数为0时,由 Py_DECREF()Py_XDECREF() 宏调用析构函数。此时,实例仍然存在,但已经没有了对它的引用。析构函数应该释放该实例拥有的所有引用,释放该实例拥有的所有内存缓冲区(通过分配内存对应的释放函数),并调用该类型的 tp_free 函数。如果该类型不可子类型化(没有设置 Py_TPFLAGS_BASETYPE 标志位),则允许直接调用对象的释放函数,不必调用 tp_free。对象的释放函数应该与分配函数对应:如果使用 PyObject_New()PyObject_VarNew() 分配,通常为 PyObject_Del();如果使用 PyObject_GC_New()PyObject_GC_NewVar() 分配,通常为 PyObject_GC_Del()

如果该类型支持垃圾回收(设置了 Py_TPFLAGS_HAVE_GC 标志位),析构器应该在清理任何成员字段之前调用 PyObject_GC_UnTrack()

static void foo_dealloc(foo_object *self) {
    PyObject_GC_UnTrack(self);
    Py_CLEAR(self->ref);
    Py_TYPE(self)->tp_free((PyObject *)self);
}

最后,如果该类型是在堆上分配的(Py_TPFLAGS_HEAPTYPE),释放器应该在调用类型释放器后减少类型对象的引用计数。为了避免空悬指针,建议的实现方法为:

static void foo_dealloc(foo_object *self) {
    PyTypeObject *tp = Py_TYPE(self);
    // free references and buffers here
    tp->tp_free(self);
    Py_DECREF(tp);
}

继承:

此字段会被子类型继承。

Py_ssize_t PyTypeObject.tp_vectorcall_offset

一个相对使用 vectorcall 协议 实现调用对象的实例级函数的可选的偏移量,这是一种比简单的 tp_call 更有效的替代选择。

This field is only used if the flag Py_TPFLAGS_HAVE_VECTORCALL is set. If so, this must be a positive integer containing the offset in the instance of a vectorcallfunc pointer.

The vectorcallfunc pointer may be NULL, in which case the instance behaves as if Py_TPFLAGS_HAVE_VECTORCALL was not set: calling the instance falls back to tp_call.

任何设置了 Py_TPFLAGS_HAVE_VECTORCALL 的类也必须设置 tp_call 并确保其行为与 vectorcallfunc 函数一致。 这可以通过将 tp_call 设为 PyVectorcall_Call() 来实现。

警告

It is not recommended for heap types to implement the vectorcall protocol. When a user sets __call__ in Python code, only tp_call is updated, likely making it inconsistent with the vectorcall function.

注解

The semantics of the tp_vectorcall_offset slot are provisional and expected to be finalized in Python 3.9. If you use vectorcall, plan for updating your code for Python 3.9.

在 3.8 版更改: 在 3.8 版之前,这个槽位被命名为 tp_print。 在 Python 2.x 中,它被用于打印到文件。 在 Python 3.0 至 3.7 中,它没有被使用。

继承:

This field is always inherited. However, the Py_TPFLAGS_HAVE_VECTORCALL flag is not always inherited. If it's not, then the subclass won't use vectorcall, except when PyVectorcall_Call() is explicitly called. This is in particular the case for heap types (including subclasses defined in Python).

getattrfunc PyTypeObject.tp_getattr

一个指向获取属性字符串函数的可选指针。

该字段已弃用。当它被定义时,应该和 tp_getattro 指向同一个函数,但接受一个C字符串参数表示属性名,而不是Python字符串对象。

继承:

分组: tp_getattr, tp_getattro

该字段会被子类和 tp_getattro 所继承:当子类型的 tp_getattrtp_getattro 均为 NULL 时该子类型将从它的基类型同时继承 tp_getattrtp_getattro

setattrfunc PyTypeObject.tp_setattr

一个指向函数以便设置和删除属性的可选指针。

该字段已弃用。当它被定义时,应该和 tp_setattro 指向同一个函数,但接受一个C字符串参数表示属性名,而不是Python字符串对象。

继承:

分组: tp_setattr, tp_setattro

该字段会被子类型和 tp_setattro 所继承:当子类型的 tp_setattrtp_setattro 均为 NULL 时该子类型将同时从它的基类型继承 tp_setattrtp_setattro

PyAsyncMethods* PyTypeObject.tp_as_async

指向一个包含仅与在 C 层级上实现 awaitableasynchronous iterator 协议的对象相关联的字段的附加结构体。 请参阅 异步对象结构体 了解详情。

3.5 新版功能: 在之前被称为 tp_comparetp_reserved

继承:

tp_as_async 字段不会被继承,但所包含的字段会被单独继承。

reprfunc PyTypeObject.tp_repr

一个实现了内置函数 repr() 的函数的可选指针。

该签名与 PyObject_Repr() 的相同:

PyObject *tp_repr(PyObject *self);

该函数必须返回一个字符串或 Unicode 对象。 在理想情况下,该函数应当返回一个字符串,当将其传给 eval() 时,只要有合适的环境,就会返回一个具有相同值的对象。 如果这不可行,则它应当返回一个以 '<' 开头并以 '>' 结尾的可被用来推断出对象的类型和值的字符串。

继承:

此字段会被子类型继承。

默认:

如果未设置该字段,则返回 <%s object at %p> 形式的字符串,其中 %s 将替换为类型名称,%p 将替换为对象的内存地址。

PyNumberMethods* PyTypeObject.tp_as_number

指向一个附加结构体的指针,其中包含只与执行数字协议的对象相关的字段。 这些字段的文档参见 数字对象结构体

继承:

tp_as_number 字段不会被继承,但所包含的字段会被单独继承。

PySequenceMethods* PyTypeObject.tp_as_sequence

指向一个附加结构体的指针,其中包含只与执行序列协议的对象相关的字段。 这些字段的文档见 序列对象结构体

继承:

tp_as_sequence 字段不会被继承,但所包含的字段会被单独继承。

PyMappingMethods* PyTypeObject.tp_as_mapping

指向一个附加结构体的指针,其中包含只与执行映射协议的对象相关的字段。 这些字段的文档见 映射对象结构体

继承:

tp_as_mapping 字段不会继承,但所包含的字段会被单独继承。

hashfunc PyTypeObject.tp_hash

一个指向实现了内置函数 hash() 的函数的可选指针。

其签名与 PyObject_Hash() 的相同:

Py_hash_t tp_hash(PyObject *);

-1 不应作为正常返回值被返回;当计算哈希值过程中发生错误时,函数应设置一个异常并返回 -1

When this field is not set (and tp_richcompare is not set), an attempt to take the hash of the object raises TypeError. This is the same as setting it to PyObject_HashNotImplemented().

此字段可被显式设为 PyObject_HashNotImplemented() 以阻止从父类型继承哈希方法。在 Python 层面这被解释为 __hash__ = None 的等价物,使得 isinstance(o, collections.Hashable) 正确返回 False.。请注意反过来也是如此:在 Python 层面设置一个类的 __hash__ = None 会使得 tp_hash 槽位被设置为 PyObject_HashNotImplemented()

继承:

Group: tp_hash, tp_richcompare

该字段会被子类型同 tp_richcompare 一起继承:当子类型的 tp_richcomparetp_hash 均为 NULL 时子类型将同时继承 tp_richcomparetp_hash

ternaryfunc PyTypeObject.tp_call

一个可选的实现对象调用的指向函数的指针。 如果对象不是可调用对象则该值应为 NULL。 其签名与 PyObject_Call() 的相同:

PyObject *tp_call(PyObject *self, PyObject *args, PyObject *kwargs);

继承:

此字段会被子类型继承。

reprfunc PyTypeObject.tp_str

一个可选的实现内置 str() 操作的函数的指针。 (请注意 str 现在是一个类型,str() 是调用该类型的构造器。 该构造器将调用 PyObject_Str() 执行实际操作,而 PyObject_Str() 将调用该处理句柄。)

其签名与 PyObject_Str() 的相同:

PyObject *tp_str(PyObject *self);

该函数必须返回一个字符串或 Unicode 对象。 它应当是一个“友好”的对象字符串表示形式,因为这就是要在 print() 函数中与其他内容一起使用的表示形式。

继承:

此字段会被子类型继承。

默认:

当未设置该字段时,将调用 PyObject_Repr() 来返回一个字符串表示形式。

getattrofunc PyTypeObject.tp_getattro

一个指向获取属性字符串函数的可选指针。

其签名与 PyObject_GetAttr() 的相同:

PyObject *tp_getattro(PyObject *self, PyObject *attr);

可以方便地将该字段设为 PyObject_GenericGetAttr(),它实现了查找对象属性的通常方式。

继承:

分组: tp_getattr, tp_getattro

该字段会被子类同 tp_getattr 一起继承:当子类型的 tp_getattrtp_getattro 均为 NULL 时子类型将同时继承 tp_getattrtp_getattro

默认:

PyBaseObject_Type uses PyObject_GenericGetAttr().

setattrofunc PyTypeObject.tp_setattro

一个指向函数以便设置和删除属性的可选指针。

其签名与 PyObject_SetAttr() 的相同:

int tp_setattro(PyObject *self, PyObject *attr, PyObject *value);

此外,还必须支持将 value 设为 NULL 来删除属性。 通常可以方便地将该字段设为 PyObject_GenericSetAttr(),它实现了设备对象属性的通常方式。

继承:

分组: tp_setattr, tp_setattro

该字段会被子类型同 tp_setattr 一起继承:当子类型的 tp_setattrtp_setattro 均为 NULL 时子类型将同时继承 tp_setattrtp_setattro

默认:

PyBaseObject_Type 使用 PyObject_GenericSetAttr().

PyBufferProcs* PyTypeObject.tp_as_buffer

指向一个包含只与实现缓冲区接口的对象相关的字段的附加结构体的指针。 这些字段的文档参见 缓冲区对象结构体

继承:

tp_as_buffer 字段不会被继承,但所包含的字段会被单独继承。

unsigned long PyTypeObject.tp_flags

该字段是针对多个旗标的位掩码。 某些旗标指明用于特定场景的变化语义;另一些旗标则用于指明类型对象(或通过 tp_as_number, tp_as_sequence, tp_as_mappingtp_as_buffer 引用的扩展结构体)中的特定字段,它们在历史上并不总是有效;如果这样的旗标位是清晰的,则它所保护的类型字段必须不可被访问并且必须被视为具有零或 NULL 值。

继承:

Inheritance of this field is complicated. Most flag bits are inherited individually, i.e. if the base type has a flag bit set, the subtype inherits this flag bit. The flag bits that pertain to extension structures are strictly inherited if the extension structure is inherited, i.e. the base type's value of the flag bit is copied into the subtype together with a pointer to the extension structure. The Py_TPFLAGS_HAVE_GC flag bit is inherited together with the tp_traverse and tp_clear fields, i.e. if the Py_TPFLAGS_HAVE_GC flag bit is clear in the subtype and the tp_traverse and tp_clear fields in the subtype exist and have NULL values.

默认:

PyBaseObject_Type uses Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE.

位掩码:

目前定义了以下位掩码;可以使用 | 运算符对它们进行 OR 运算以形成 tp_flags 字段的值。 宏 PyType_HasFeature() 接受一个类型和一个旗标值 tpf,并检查 tp->tp_flags & f 是否为非零值。

Py_TPFLAGS_HEAPTYPE

This bit is set when the type object itself is allocated on the heap, for example, types created dynamically using PyType_FromSpec(). In this case, the ob_type field of its instances is considered a reference to the type, and the type object is INCREF'ed when a new instance is created, and DECREF'ed when an instance is destroyed (this does not apply to instances of subtypes; only the type referenced by the instance's ob_type gets INCREF'ed or DECREF'ed).

继承:

???

Py_TPFLAGS_BASETYPE

当此类型可被用作另一个类型的基类型时该比特位将被设置。 如果该比特位被清除,则此类型将无法被子类型化(类似于 Java 中的 "final" 类)。

继承:

???

Py_TPFLAGS_READY

当此类型对象通过 PyType_Ready() 被完全实例化时该比特位将被设置。

继承:

???

Py_TPFLAGS_READYING

PyType_Ready() 处在初始化此类型对象过程中时该比特位将被设置。

继承:

???

Py_TPFLAGS_HAVE_GC

当此对象支持垃圾回收时该比特位将被设置。 如果设置了该比特位,则实例必须使用 PyObject_GC_New() 来创建并使用 PyObject_GC_Del() 来销毁。 更多信息见 使对象类型支持循环垃圾回收 一节。 该比特位还表明与类型对象中存在 GC 相关字段 tp_traversetp_clear

继承:

分组: Py_TPFLAGS_HAVE_GC, tp_traverse, tp_clear

The Py_TPFLAGS_HAVE_GC flag bit is inherited together with the tp_traverse and tp_clear fields, i.e. if the Py_TPFLAGS_HAVE_GC flag bit is clear in the subtype and the tp_traverse and tp_clear fields in the subtype exist and have NULL values.

Py_TPFLAGS_DEFAULT

This is a bitmask of all the bits that pertain to the existence of certain fields in the type object and its extension structures. Currently, it includes the following bits: Py_TPFLAGS_HAVE_STACKLESS_EXTENSION, Py_TPFLAGS_HAVE_VERSION_TAG.

继承:

???

Py_TPFLAGS_METHOD_DESCRIPTOR

这个位指明对象的行为类似于未绑定方法。

如果为 type(meth) 设置了该旗标,那么:

  • meth.__get__(obj, cls)(*args, **kwds) (其中 obj 不为 None) 必须等价于 meth(obj, *args, **kwds)

  • meth.__get__(None, cls)(*args, **kwds) 必须等价于 meth(*args, **kwds)

此旗标为 obj.meth() 这样的典型方法调用启用优化:它将避免为 obj.meth 创建临时的“绑定方法”对象。

3.8 新版功能.

继承:

This flag is never inherited by heap types. For extension types, it is inherited whenever tp_descr_get is inherited.

Py_TPFLAGS_LONG_SUBCLASS
Py_TPFLAGS_LIST_SUBCLASS
Py_TPFLAGS_TUPLE_SUBCLASS
Py_TPFLAGS_BYTES_SUBCLASS
Py_TPFLAGS_UNICODE_SUBCLASS
Py_TPFLAGS_DICT_SUBCLASS
Py_TPFLAGS_BASE_EXC_SUBCLASS
Py_TPFLAGS_TYPE_SUBCLASS

这些旗标被 PyLong_Check() 等函数用来快速确定一个类型是否为内置类型的子类;这样的专用检测比泛用检测如 PyObject_IsInstance() 要更快速。 继承自内置类型的自定义类型应当正确地设置其 tp_flags,否则与这样的类型进行交互的代码将因所使用的检测种类而出现不同的行为。

Py_TPFLAGS_HAVE_FINALIZE

当类型结构体中存在 tp_finalize 槽位时会设置这个比特位。

3.4 新版功能.

3.8 版后已移除: 此旗标已不再是必要的,因为解释器会假定类型结构体中总是存在 tp_finalize 槽位。

Py_TPFLAGS_HAVE_VECTORCALL

当类实现了 vectorcall 协议 时会设置这个比特位。 请参阅 tp_vectorcall_offset 了解详情。

继承:

This bit is inherited for static subtypes if tp_call is also inherited. Heap types do not inherit Py_TPFLAGS_HAVE_VECTORCALL.

3.9 新版功能.

const char* PyTypeObject.tp_doc

一个可选的指向给出该类型对象的文档字符串的以 NUL 结束的 C 字符串的指针。 该指针被暴露为类型和类型实例上的 __doc__ 属性。

继承:

这个字段 不会 被子类型继承。

traverseproc PyTypeObject.tp_traverse

An optional pointer to a traversal function for the garbage collector. This is only used if the Py_TPFLAGS_HAVE_GC flag bit is set. The signature is:

int tp_traverse(PyObject *self, visitproc visit, void *arg);

有关 Python 垃圾回收方案的更多信息可在 使对象类型支持循环垃圾回收 一节中查看。

The tp_traverse pointer is used by the garbage collector to detect reference cycles. A typical implementation of a tp_traverse function simply calls Py_VISIT() on each of the instance's members that are Python objects that the instance owns. For example, this is function local_traverse() from the _thread extension module:

static int
local_traverse(localobject *self, visitproc visit, void *arg)
{
    Py_VISIT(self->args);
    Py_VISIT(self->kw);
    Py_VISIT(self->dict);
    return 0;
}

请注意 Py_VISIT() 仅能在可以参加循环引用的成员上被调用。 虽然还存在一个 self->key 成员,但它只能为 NULL 或 Python 字符串因而不能成为循环引用的一部分。

在另一方面,即使你知道某个成员永远不会成为循环引用的一部分,作为调试的辅助你仍然可能想要访问它因此 gc 模块的 get_referents() 函数将会包括它。

警告

When implementing tp_traverse, only the members that the instance owns (by having strong references to them) must be visited. For instance, if an object supports weak references via the tp_weaklist slot, the pointer supporting the linked list (what tp_weaklist points to) must not be visited as the instance does not directly own the weak references to itself (the weakreference list is there to support the weak reference machinery, but the instance has no strong reference to the elements inside it, as they are allowed to be removed even if the instance is still alive).

请注意 Py_VISIT() 要求传给 local_traverse()visitarg 形参具有指定的名称;不要随意命名它们。

Heap-allocated types (Py_TPFLAGS_HEAPTYPE, such as those created with PyType_FromSpec() and similar APIs) hold a reference to their type. Their traversal function must therefore either visit Py_TYPE(self), or delegate this responsibility by calling tp_traverse of another heap-allocated type (such as a heap-allocated superclass). If they do not, the type object may not be garbage-collected.

在 3.9 版更改: 堆分配类型应当访问 tp_traverse 中的 Py_TYPE(self)。 在较早的 Python 版本中,由于 bug 40217,这样做可能会导致在超类中发生崩溃。

继承:

分组: Py_TPFLAGS_HAVE_GC, tp_traverse, tp_clear

This field is inherited by subtypes together with tp_clear and the Py_TPFLAGS_HAVE_GC flag bit: the flag bit, tp_traverse, and tp_clear are all inherited from the base type if they are all zero in the subtype.

inquiry PyTypeObject.tp_clear

An optional pointer to a clear function for the garbage collector. This is only used if the Py_TPFLAGS_HAVE_GC flag bit is set. The signature is:

int tp_clear(PyObject *);

tp_clear 成员函数被用来打破垃圾回收器在循环垃圾中检测到的循环引用。 总的来说,系统中的所有 tp_clear 函数必须合到一起以打破所有引用循环。 这是个微妙的问题,并且如有任何疑问都需要提供 tp_clear 函数。 例如,元组类型不会实现 tp_clear 函数,因为有可能证明完全用元组是不会构成循环引用的。 因此其他类型的 tp_clear 函数必须足以打破任何包含元组的循环。 这不是立即能明确的,并且很少会有避免实现 tp_clear 的适当理由。

tp_clear 的实现应当丢弃实例指向其成员的可能为 Python 对象的引用,并将指向这些成员的指针设为 NULL,如下面的例子所示:

static int
local_clear(localobject *self)
{
    Py_CLEAR(self->key);
    Py_CLEAR(self->args);
    Py_CLEAR(self->kw);
    Py_CLEAR(self->dict);
    return 0;
}

The Py_CLEAR() macro should be used, because clearing references is delicate: the reference to the contained object must not be decremented until after the pointer to the contained object is set to NULL. This is because decrementing the reference count may cause the contained object to become trash, triggering a chain of reclamation activity that may include invoking arbitrary Python code (due to finalizers, or weakref callbacks, associated with the contained object). If it's possible for such code to reference self again, it's important that the pointer to the contained object be NULL at that time, so that self knows the contained object can no longer be used. The Py_CLEAR() macro performs the operations in a safe order.

请注意 tp_clear 并非 总是 在实例被取消分配之前被调用。 例如,当引用计数足以确定对象不再被使用时,就不会涉及循环垃圾回收器而是直接调用 tp_dealloc

因为 tp_clear 函数的目的是打破循环引用,所以不需要清除所包含的对象如 Python 字符串或 Python 整数,它们无法参与循环引用。 另一方面,清除所包含的全部 Python 对象,并编写类型的 tp_dealloc 函数来发起调用 tp_clear 也很方便。

有关 Python 垃圾回收方案的更多信息可在 使对象类型支持循环垃圾回收 一节中查看。

继承:

分组: Py_TPFLAGS_HAVE_GC, tp_traverse, tp_clear

This field is inherited by subtypes together with tp_traverse and the Py_TPFLAGS_HAVE_GC flag bit: the flag bit, tp_traverse, and tp_clear are all inherited from the base type if they are all zero in the subtype.

richcmpfunc PyTypeObject.tp_richcompare

一个可选的指向富比较函数的指针,函数的签名为:

PyObject *tp_richcompare(PyObject *self, PyObject *other, int op);

第一个形参将保证为 PyTypeObject 所定义的类型的实例。

该函数应当返回比较的结果 (通常为 Py_TruePy_False)。 如果未定义比较运算,它必须返回 Py_NotImplemented,如果发生了其他错误则它必须返回 NULL 并设置一个异常条件。

以下常量被定义用作 tp_richcomparePyObject_RichCompare() 的第三个参数:

常量

对照

Py_LT

<

Py_LE

<=

Py_EQ

==

Py_NE

!=

Py_GT

>

Py_GE

>=

定义以下宏是为了简化编写丰富的比较函数:

Py_RETURN_RICHCOMPARE(VAL_A, VAL_B, op)

从该函数返回 Py_TruePy_False,这取决于比较的结果。 VAL_A 和 VAL_B 必须是可通过 C 比较运算符进行排序的(例如,它们可以为 C 整数或浮点数)。 第三个参数指明所请求的运算,与 PyObject_RichCompare() 的参数一样。

The return value's reference count is properly incremented.

发生错误时,将设置异常并从该函数返回 NULL

3.7 新版功能.

继承:

Group: tp_hash, tp_richcompare

该字段会被子类型同 tp_hash 一起继承:当子类型的 tp_richcomparetp_hash 均为 NULL 时子类型将同时继承 tp_richcomparetp_hash

默认:

PyBaseObject_Type provides a tp_richcompare implementation, which may be inherited. However, if only tp_hash is defined, not even the inherited function is used and instances of the type will not be able to participate in any comparisons.

Py_ssize_t PyTypeObject.tp_weaklistoffset

If the instances of this type are weakly referenceable, this field is greater than zero and contains the offset in the instance structure of the weak reference list head (ignoring the GC header, if present); this offset is used by PyObject_ClearWeakRefs() and the PyWeakref_*() functions. The instance structure needs to include a field of type PyObject* which is initialized to NULL.

不要将该字段与 tp_weaklist 混淆;后者是指向类型对象本身的弱引用的列表头。

继承:

该字段会被子类型继承,但注意参阅下面列出的规则。 子类型可以覆盖此偏移量;这意味着子类型将使用不同于基类型的弱引用列表。 由于列表头总是通过 tp_weaklistoffset 找到的,所以这应该不成问题。

When a type defined by a class statement has no __slots__ declaration, and none of its base types are weakly referenceable, the type is made weakly referenceable by adding a weak reference list head slot to the instance layout and setting the tp_weaklistoffset of that slot's offset.

When a type's __slots__ declaration contains a slot named __weakref__, that slot becomes the weak reference list head for instances of the type, and the slot's offset is stored in the type's tp_weaklistoffset.

When a type's __slots__ declaration does not contain a slot named __weakref__, the type inherits its tp_weaklistoffset from its base type.

getiterfunc PyTypeObject.tp_iter

An optional pointer to a function that returns an iterator for the object. Its presence normally signals that the instances of this type are iterable (although sequences may be iterable without this function).

此函数的签名与 PyObject_GetIter() 的相同:

PyObject *tp_iter(PyObject *self);

继承:

此字段会被子类型继承。

iternextfunc PyTypeObject.tp_iternext

An optional pointer to a function that returns the next item in an iterator. The signature is:

PyObject *tp_iternext(PyObject *self);

当该迭代器被耗尽时,它必须返回 NULLStopIteration 异常可能会设置也可能不设置。 当发生另一个错误时,它也必须返回 NULL。 它的存在表明该类型的实际是迭代器。

迭代器类型也应当定义 tp_iter 函数,并且该函数应当返回迭代器实例本身(而不是新的迭代器实例)。

此函数的签名与 PyIter_Next() 的相同。

继承:

此字段会被子类型继承。

struct PyMethodDef* PyTypeObject.tp_methods

一个可选的指向 PyMethodDef 结构体的以 NULL 结束的静态数组的指针,它声明了此类型的常规方法。

对于该数组中的每一项,都会向类型的字典 (参见下面的 tp_dict) 添加一个包含方法描述器的条目。

继承:

该字段不会被子类型所继承(方法是通过不同的机制来继承的)。

struct PyMemberDef* PyTypeObject.tp_members

一个可选的指向 PyMemberDef 结构体的以 NULL 结束的静态数组的指针,它声明了此类型的常规数据成员(字段或槽位)。

对于该数组中的每一项,都会向类型的字典 (参见下面的 tp_dict) 添加一个包含方法描述器的条目。

继承:

该字段不会被子类型所继承(成员是通过不同的机制来继承的)。

struct PyGetSetDef* PyTypeObject.tp_getset

一个可选的指向 PyGetSetDef 结构体的以 NULL 结束的静态数组的指针,它声明了此类型的实例中的被计算属性。

对于该数组中的每一项,都会向类型的字典 (参见下面的 tp_dict) 添加一个包含读写描述器的条目。

继承:

该字段不会被子类型所继承(被计算属性是通过不同的机制来继承的)。

PyTypeObject* PyTypeObject.tp_base

一个可选的指向类型特征属性所继承的基类型的指针。 在这个层级上,只支持单继承;多重继承需要通过调用元类型动态地创建类型对象。

注解

槽位初始化需要遵循初始化全局变量的规则。 C99 要求初始化器为“地址常量”。 隐式转换为指针的函数指示器如 PyType_GenericNew() 都是有效的 C99 地址常量。

However, the unary '&' operator applied to a non-static variable like PyBaseObject_Type() is not required to produce an address constant. Compilers may support this (gcc does), MSVC does not. Both compilers are strictly standard conforming in this particular behavior.

因此,应当在扩展模块的初始化函数中设置 tp_base

继承:

该字段不会被子类型继承(显然)。

默认:

该字段默认为 &PyBaseObject_Type (对 Python 程序员来说即 object 类型)。

PyObject* PyTypeObject.tp_dict

类型的字典将由 PyType_Ready() 存储到这里。

This field should normally be initialized to NULL before PyType_Ready is called; it may also be initialized to a dictionary containing initial attributes for the type. Once PyType_Ready() has initialized the type, extra attributes for the type may be added to this dictionary only if they don't correspond to overloaded operations (like __add__()).

继承:

该字段不会被子类型所继承(但在这里定义的属性是通过不同的机制来继承的)。

默认:

如果该字段为 NULLPyType_Ready() 将为它分配一个新字典。

警告

通过字典 C-API 使用 PyDict_SetItem() 或修改 tp_dict 是不安全的。

descrgetfunc PyTypeObject.tp_descr_get

一个可选的指向“描述器获取”函数的指针。

函数的签名为:

PyObject * tp_descr_get(PyObject *self, PyObject *obj, PyObject *type);

继承:

此字段会被子类型继承。

descrsetfunc PyTypeObject.tp_descr_set

一个指向用于设置和删除描述器值的函数的选项指针。

函数的签名为:

int tp_descr_set(PyObject *self, PyObject *obj, PyObject *value);

value 参数设为 NULL 以删除该值。

继承:

此字段会被子类型继承。

Py_ssize_t PyTypeObject.tp_dictoffset

如果该类型的实例具有一个包含实例变量的字典,则此字段将为非零值并包含该实例变量字典的类型的实例的偏移量;该偏移量将由 PyObject_GenericGetAttr() 使用。

不要将该字段与 tp_dict 混淆;后者是由类型对象本身的属性组成的字典。

If the value of this field is greater than zero, it specifies the offset from the start of the instance structure. If the value is less than zero, it specifies the offset from the end of the instance structure. A negative offset is more expensive to use, and should only be used when the instance structure contains a variable-length part. This is used for example to add an instance variable dictionary to subtypes of str or tuple. Note that the tp_basicsize field should account for the dictionary added to the end in that case, even though the dictionary is not included in the basic object layout. On a system with a pointer size of 4 bytes, tp_dictoffset should be set to -4 to indicate that the dictionary is at the very end of the structure.

The real dictionary offset in an instance can be computed from a negative tp_dictoffset as follows:

dictoffset = tp_basicsize + abs(ob_size)*tp_itemsize + tp_dictoffset
if dictoffset is not aligned on sizeof(void*):
    round up to sizeof(void*)

where tp_basicsize, tp_itemsize and tp_dictoffset are taken from the type object, and ob_size is taken from the instance. The absolute value is taken because ints use the sign of ob_size to store the sign of the number. (There's never a need to do this calculation yourself; it is done for you by _PyObject_GetDictPtr().)

继承:

This field is inherited by subtypes, but see the rules listed below. A subtype may override this offset; this means that the subtype instances store the dictionary at a difference offset than the base type. Since the dictionary is always found via tp_dictoffset, this should not be a problem.

When a type defined by a class statement has no __slots__ declaration, and none of its base types has an instance variable dictionary, a dictionary slot is added to the instance layout and the tp_dictoffset is set to that slot's offset.

When a type defined by a class statement has a __slots__ declaration, the type inherits its tp_dictoffset from its base type.

(Adding a slot named __dict__ to the __slots__ declaration does not have the expected effect, it just causes confusion. Maybe this should be added as a feature just like __weakref__ though.)

默认:

This slot has no default. For static types, if the field is NULL then no __dict__ gets created for instances.

initproc PyTypeObject.tp_init

一个可选的指向实例初始化函数的指针。

This function corresponds to the __init__() method of classes. Like __init__(), it is possible to create an instance without calling __init__(), and it is possible to reinitialize an instance by calling its __init__() method again.

函数的签名为:

int tp_init(PyObject *self, PyObject *args, PyObject *kwds);

The self argument is the instance to be initialized; the args and kwds arguments represent positional and keyword arguments of the call to __init__().

tp_init 函数如果不为 NULL,将在通过调用类型正常创建其实例时被调用,即在类型的 tp_new 函数返回一个该类型的实例时。 如果 tp_new 函数返回了一个不是原始类型的子类型的其他类型的实例,则 tp_init 函数不会被调用;如果 tp_new 返回了一个原始类型的子类型的实例,则该子类型的 tp_init 将被调用。

成功时返回 0,发生错误时则返回 -1 并在错误上设置一个异常。and sets an exception on error.

继承:

此字段会被子类型继承。

默认:

For static types this field does not have a default.

allocfunc PyTypeObject.tp_alloc

指向一个实例分配函数的可选指针。

函数的签名为:

PyObject *tp_alloc(PyTypeObject *self, Py_ssize_t nitems);

继承:

该字段会被静态子类型继承,但不会被动态子类型(通过 class 语句创建的子类型)继承。

默认:

对于动态子类型,该字段总是会被设为 PyType_GenericAlloc(),以强制应用标准的堆分配策略。

For static subtypes, PyBaseObject_Type uses PyType_GenericAlloc(). That is the recommended value for all statically defined types.

newfunc PyTypeObject.tp_new

一个可选的指向实例创建函数的指针。

函数的签名为:

PyObject *tp_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds);

subtype 参数是被创建的对象的类型;argskwds 参数表示调用类型时传入的位置和关键字参数。 请注意 subtype 不是必须与被调用的 tp_new 函数所属的类型相同;它可以是该类型的子类型(但不能是完全无关的类型)。

tp_new 函数应当调用 subtype->tp_alloc(subtype, nitems) 来为对象分配空间,然后只执行绝对有必要的进一步初始化操作。 可以安全地忽略或重复的初始化操作应当放在 tp_init 处理句柄中。 一个关键的规则是对于不可变类型来说,所有初始化操作都应当在 tp_new 中发生,而对于可变类型,大部分初始化操作都应当推迟到 tp_init 再执行。

继承:

This field is inherited by subtypes, except it is not inherited by static types whose tp_base is NULL or &PyBaseObject_Type.

默认:

For static types this field has no default. This means if the slot is defined as NULL, the type cannot be called to create new instances; presumably there is some other way to create instances, like a factory function.

freefunc PyTypeObject.tp_free

一个可选的指向实例释放函数的指针。 函数的签名为:

void tp_free(void *self);

一个兼容该签名的初始化器是 PyObject_Free()

继承:

该字段会被静态子类型继承,但不会被动态子类型(通过 class 语句创建的子类型)继承

默认:

In dynamic subtypes, this field is set to a deallocator suitable to match PyType_GenericAlloc() and the value of the Py_TPFLAGS_HAVE_GC flag bit.

对于静态子类型,PyBaseObject_Type 使用 PyObject_Del.

inquiry PyTypeObject.tp_is_gc

可选的指向垃圾回收器所调用的函数的指针。

The garbage collector needs to know whether a particular object is collectible or not. Normally, it is sufficient to look at the object's type's tp_flags field, and check the Py_TPFLAGS_HAVE_GC flag bit. But some types have a mixture of statically and dynamically allocated instances, and the statically allocated instances are not collectible. Such types should define this function; it should return 1 for a collectible instance, and 0 for a non-collectible instance. The signature is:

int tp_is_gc(PyObject *self);

(The only example of this are types themselves. The metatype, PyType_Type, defines this function to distinguish between statically and dynamically allocated types.)

继承:

此字段会被子类型继承。

默认:

This slot has no default. If this field is NULL, Py_TPFLAGS_HAVE_GC is used as the functional equivalent.

PyObject* PyTypeObject.tp_bases

基类型的元组。

This is set for types created by a class statement. It should be NULL for statically defined types.

继承:

这个字段不会被继承。

PyObject* PyTypeObject.tp_mro

包含基类型的扩展集的元组,以类型本身开始并以 object 作为结束,使用方法解析顺序。

继承:

这个字段不会被继承;它是通过 PyType_Ready() 计算得到的。

PyObject* PyTypeObject.tp_cache

尚未使用。 仅供内部使用。

继承:

这个字段不会被继承。

PyObject* PyTypeObject.tp_subclasses

由对子类的弱引用组成的列表。 仅供内部使用。

继承:

这个字段不会被继承。

PyObject* PyTypeObject.tp_weaklist

弱引用列表头,用于指向该类型对象的弱引用。 不会被继承。 仅限内部使用。

继承:

这个字段不会被继承。

destructor PyTypeObject.tp_del

该字段已被弃用。 请改用 tp_finalize

unsigned int PyTypeObject.tp_version_tag

用于索引至方法缓存。 仅限内部使用。

继承:

这个字段不会被继承。

destructor PyTypeObject.tp_finalize

一个可选的指向实例最终化函数的指针。 函数的签名为:

void tp_finalize(PyObject *self);

如果设置了 tp_finalize,解释器将在最终化特定实例时调用它一次。 它将由垃圾回收器调用(如果实例是单独循环引用的一部分)或是在对象被释放之前被调用。 不论是哪种方式,它都肯定会在尝试打破循环引用之前被调用,以确保它所操作的对象处于正常状态。

tp_finalize 不应改变当前异常状态;因此,编写非关键终结器的推荐做法如下:

static void
local_finalize(PyObject *self)
{
    PyObject *error_type, *error_value, *error_traceback;

    /* Save the current exception, if any. */
    PyErr_Fetch(&error_type, &error_value, &error_traceback);

    /* ... */

    /* Restore the saved exception. */
    PyErr_Restore(error_type, error_value, error_traceback);
}

For this field to be taken into account (even through inheritance), you must also set the Py_TPFLAGS_HAVE_FINALIZE flags bit.

另外还需要注意,在应用垃圾回收机制的 Python 中,tp_dealloc 可以从任意 Python 线程被调用,而不仅是创建该对象的线程(如果对象成为引用计数循环的一部分,则该循环可能会被任何线程上的垃圾回收操作所回收)。 这对 Python API 调用来说不是问题,因为 tp_dealloc 调用所在的线程将持有全局解释器锁(GIL)。 但是,如果被销毁的对象又销毁了来自其他 C 或 C++ 库的对象,则应当小心确保在调用 tp_dealloc 的线程上销毁这些对象不会破坏这些库的任何资源。

继承:

此字段会被子类型继承。

3.4 新版功能.

参见

"安全的对象最终化" (PEP 442)

vectorcallfunc PyTypeObject.tp_vectorcall

Vectorcall function to use for calls of this type object. In other words, it is used to implement vectorcall for type.__call__. If tp_vectorcall is NULL, the default call implementation using __new__ and __init__ is used.

继承:

这个字段不会被继承。

3.9 新版功能: (这个字段从 3.8 起即存在,但是从 3.9 开始投入使用)

堆类型

在传统上,在 C 代码中定义的类型都是 静态的,也就是说,PyTypeObject 结构体在代码中直接定义并使用 PyType_Ready() 来初始化。

这就导致了与在 Python 中定义的类型相关联的类型限制:

  • 静态类型只能拥有一个基类;换句话说,他们不能使用多重继承。

  • 静态类型对象(但并非它们的实例)是不可变对象。 不可能在 Python 中添加或修改类型对象的属性。

  • 静态类型对象是跨 子解释器 共享的,因此它们不应包括任何子解释器专属的状态。

Also, since PyTypeObject is not part of the stable ABI, any extension modules using static types must be compiled for a specific Python minor version.

An alternative to static types is heap-allocated types, or heap types for short, which correspond closely to classes created by Python's class statement.

This is done by filling a PyType_Spec structure and calling PyType_FromSpecWithBases().

数字对象结构体

PyNumberMethods

该结构体持有指向被对象用来实现数字协议的函数的指针。 每个函数都被 数字协议 一节中记录的对应名称的函数所使用。

结构体定义如下:

typedef struct {
     binaryfunc nb_add;
     binaryfunc nb_subtract;
     binaryfunc nb_multiply;
     binaryfunc nb_remainder;
     binaryfunc nb_divmod;
     ternaryfunc nb_power;
     unaryfunc nb_negative;
     unaryfunc nb_positive;
     unaryfunc nb_absolute;
     inquiry nb_bool;
     unaryfunc nb_invert;
     binaryfunc nb_lshift;
     binaryfunc nb_rshift;
     binaryfunc nb_and;
     binaryfunc nb_xor;
     binaryfunc nb_or;
     unaryfunc nb_int;
     void *nb_reserved;
     unaryfunc nb_float;

     binaryfunc nb_inplace_add;
     binaryfunc nb_inplace_subtract;
     binaryfunc nb_inplace_multiply;
     binaryfunc nb_inplace_remainder;
     ternaryfunc nb_inplace_power;
     binaryfunc nb_inplace_lshift;
     binaryfunc nb_inplace_rshift;
     binaryfunc nb_inplace_and;
     binaryfunc nb_inplace_xor;
     binaryfunc nb_inplace_or;

     binaryfunc nb_floor_divide;
     binaryfunc nb_true_divide;
     binaryfunc nb_inplace_floor_divide;
     binaryfunc nb_inplace_true_divide;

     unaryfunc nb_index;

     binaryfunc nb_matrix_multiply;
     binaryfunc nb_inplace_matrix_multiply;
} PyNumberMethods;

注解

双目和三目函数必须检查其所有操作数的类型,并实现必要的转换(至少有一个操作数是所定义类型的实例)。 如果没有为所给出的操作数定义操作,则双目和三目函数必须返回 Py_NotImplemented,如果发生了其他错误则它们必须返回 NULL 并设置一个异常。

注解

The nb_reserved field should always be NULL. It was previously called nb_long, and was renamed in Python 3.0.1.

binaryfunc PyNumberMethods.nb_add
binaryfunc PyNumberMethods.nb_subtract
binaryfunc PyNumberMethods.nb_multiply
binaryfunc PyNumberMethods.nb_remainder
binaryfunc PyNumberMethods.nb_divmod
ternaryfunc PyNumberMethods.nb_power
unaryfunc PyNumberMethods.nb_negative
unaryfunc PyNumberMethods.nb_positive
unaryfunc PyNumberMethods.nb_absolute
inquiry PyNumberMethods.nb_bool
unaryfunc PyNumberMethods.nb_invert
binaryfunc PyNumberMethods.nb_lshift
binaryfunc PyNumberMethods.nb_rshift
binaryfunc PyNumberMethods.nb_and
binaryfunc PyNumberMethods.nb_xor
binaryfunc PyNumberMethods.nb_or
unaryfunc PyNumberMethods.nb_int
void *PyNumberMethods.nb_reserved
unaryfunc PyNumberMethods.nb_float
binaryfunc PyNumberMethods.nb_inplace_add
binaryfunc PyNumberMethods.nb_inplace_subtract
binaryfunc PyNumberMethods.nb_inplace_multiply
binaryfunc PyNumberMethods.nb_inplace_remainder
ternaryfunc PyNumberMethods.nb_inplace_power
binaryfunc PyNumberMethods.nb_inplace_lshift
binaryfunc PyNumberMethods.nb_inplace_rshift
binaryfunc PyNumberMethods.nb_inplace_and
binaryfunc PyNumberMethods.nb_inplace_xor
binaryfunc PyNumberMethods.nb_inplace_or
binaryfunc PyNumberMethods.nb_floor_divide
binaryfunc PyNumberMethods.nb_true_divide
binaryfunc PyNumberMethods.nb_inplace_floor_divide
binaryfunc PyNumberMethods.nb_inplace_true_divide
unaryfunc PyNumberMethods.nb_index
binaryfunc PyNumberMethods.nb_matrix_multiply
binaryfunc PyNumberMethods.nb_inplace_matrix_multiply

映射对象结构体

PyMappingMethods

该结构体持有指向对象用于实现映射协议的函数的指针。 它有三个成员:

lenfunc PyMappingMethods.mp_length

该函数将被 PyMapping_Size()PyObject_Size() 使用,并具有相同的签名。 如果对象没有定义长度则此槽位可被设为 NULL

binaryfunc PyMappingMethods.mp_subscript

该函数将被 PyObject_GetItem()PySequence_GetSlice() 使用,并具有与 PyObject_GetItem() 相同的签名。 此槽位必须被填充以便 PyMapping_Check() 函数返回 1,否则它可以为 NULL

objobjargproc PyMappingMethods.mp_ass_subscript

This function is used by PyObject_SetItem(), PyObject_DelItem(), PyObject_SetSlice() and PyObject_DelSlice(). It has the same signature as PyObject_SetItem(), but v can also be set to NULL to delete an item. If this slot is NULL, the object does not support item assignment and deletion.

序列对象结构体

PySequenceMethods

该结构体持有指向对象用于实现序列协议的函数的指针。

lenfunc PySequenceMethods.sq_length

此函数被 PySequence_Size()PyObject_Size() 所使用,并具有与它们相同的签名。 它还被用于通过 sq_itemsq_ass_item 槽位来处理负索引号。

binaryfunc PySequenceMethods.sq_concat

此函数被 PySequence_Concat() 所使用并具有相同的签名。 在尝试通过 nb_add 槽位执行数值相加之后它还会被用于 + 运算符。

ssizeargfunc PySequenceMethods.sq_repeat

此函数被 PySequence_Repeat() 所使用并具有相同的签名。 在尝试通过 nb_multiply 槽位执行数值相乘之后它还会被用于 * 运算符。

ssizeargfunc PySequenceMethods.sq_item

此函数被 PySequence_GetItem() 所使用并具有相同的签名。 在尝试通过 mp_subscript 槽位执行下标操作之后它还会被用于 PyObject_GetItem()。 该槽位必须被填充以便 PySequence_Check() 函数返回 1,否则它可以为 NULL

Negative indexes are handled as follows: if the sq_length slot is filled, it is called and the sequence length is used to compute a positive index which is passed to sq_item. If sq_length is NULL, the index is passed as is to the function.

ssizeobjargproc PySequenceMethods.sq_ass_item

此函数被 PySequence_SetItem() 所使用并具有相同的签名。 在尝试通过 mp_ass_subscript 槽位执行条目赋值和删除操作之后它还会被用于 PyObject_SetItem()PyObject_DelItem()。 如果对象不支持条目和删除则该槽位可以保持为 NULL

objobjproc PySequenceMethods.sq_contains

该函数可供 PySequence_Contains() 使用并具有相同的签名。 此槽位可以保持为 NULL,在此情况下 PySequence_Contains() 只需遍历该序列直到找到一个匹配。

binaryfunc PySequenceMethods.sq_inplace_concat

此函数被 PySequence_InPlaceConcat() 所使用并具有相同的签名。 它应当修改它的第一个操作数,并将其返回。 该槽位可以保持为 NULL,在此情况下 PySequence_InPlaceConcat() 将回退到 PySequence_Concat()。 在尝试通过 nb_inplace_add 槽位执行数字原地相加之后它还会被用于增强赋值运算符 +=

ssizeargfunc PySequenceMethods.sq_inplace_repeat

此函数被 PySequence_InPlaceRepeat() 所使用并具有相同的签名。 它应当修改它的第一个操作数,并将其返回。 该槽位可以保持为 NULL,在此情况下 PySequence_InPlaceRepeat() 将回退到 PySequence_Repeat()。 在尝试通过 nb_inplace_multiply 槽位执行数字原地相乘之后它还会被用于增强赋值运算符 *=

缓冲区对象结构体

PyBufferProcs

此结构体持有指向 缓冲区协议 所需要的函数的指针。 该协议定义了导出方对象要如何向消费方对象暴露其内部数据。

getbufferproc PyBufferProcs.bf_getbuffer

此函数的签名为:

int (PyObject *exporter, Py_buffer *view, int flags);

处理发给 exporter 的请求来填充 flags 所指定的 view。 除第 (3) 点外,此函数的实现必须执行以下步骤:

  1. Check if the request can be met. If not, raise PyExc_BufferError, set view->obj to NULL and return -1.

  2. 填充请求的字段。

  3. 递增用于保存导出次数的内部计数器。

  4. Set view->obj to exporter and increment view->obj.

  5. 返回 0

如果 exporter 是缓冲区提供方的链式或树型结构的一部分,则可以使用两种主要方案:

  • Re-export: Each member of the tree acts as the exporting object and sets view->obj to a new reference to itself.

  • Redirect: The buffer request is redirected to the root object of the tree. Here, view->obj will be a new reference to the root object.

view 中每个字段的描述参见 缓冲区结构体 一节,导出方对于特定请求应当如何反应参见 缓冲区请求类型 一节。

所有在 Py_buffer 结构体中被指向的内存都属于导出方并必须保持有效直到不再有任何消费方。 format, shape, strides, suboffsetsinternal 对于消费方来说是只读的。

PyBuffer_FillInfo() 提供了一种暴露简单字节缓冲区同时正确处理地所有请求类型的简便方式。

PyObject_GetBuffer() 是针对包装此函数的消费方的接口。

releasebufferproc PyBufferProcs.bf_releasebuffer

此函数的签名为:

void (PyObject *exporter, Py_buffer *view);

处理释放缓冲区资源的请求。 如果不需要释放任何资源,则 PyBufferProcs.bf_releasebuffer 可以为 NULL。 在其他情况下,此函数的标准实现将执行以下的可选步骤:

  1. 递减用于保存导出次数的内部计数器。

  2. 如果计数器为 0,则释放所有关联到 view 的内存。

导出方必须使用 internal 字段来记录缓冲区专属的资源。 该字段将确保恒定,而消费方则可能将原始缓冲区作为 view 参数传入。

This function MUST NOT decrement view->obj, since that is done automatically in PyBuffer_Release() (this scheme is useful for breaking reference cycles).

PyBuffer_Release() 是针对包装此函数的消费方的接口。

异步对象结构体

3.5 新版功能.

PyAsyncMethods

此结构体将持有指向需要用来实现 awaitableasynchronous iterator 对象的函数的指针。

结构体定义如下:

typedef struct {
    unaryfunc am_await;
    unaryfunc am_aiter;
    unaryfunc am_anext;
} PyAsyncMethods;
unaryfunc PyAsyncMethods.am_await

此函数的签名为:

PyObject *am_await(PyObject *self);

The returned object must be an iterator, i.e. PyIter_Check() must return 1 for it.

如果一个对象不是 awaitable 则此槽位可被设为 NULL

unaryfunc PyAsyncMethods.am_aiter

此函数的签名为:

PyObject *am_aiter(PyObject *self);

必须返回一个 asynchronous iterator 对象。 请参阅 __anext__() 了解详情。

如果一个对象没有实现异步迭代协议则此槽位可被设为 NULL

unaryfunc PyAsyncMethods.am_anext

此函数的签名为:

PyObject *am_anext(PyObject *self);

Must return an awaitable object. See __anext__() for details. This slot may be set to NULL.

槽位类型 typedef

PyObject *(*allocfunc)(PyTypeObject *cls, Py_ssize_t nitems)

The purpose of this function is to separate memory allocation from memory initialization. It should return a pointer to a block of memory of adequate length for the instance, suitably aligned, and initialized to zeros, but with ob_refcnt set to 1 and ob_type set to the type argument. If the type's tp_itemsize is non-zero, the object's ob_size field should be initialized to nitems and the length of the allocated memory block should be tp_basicsize + nitems*tp_itemsize, rounded up to a multiple of sizeof(void*); otherwise, nitems is not used and the length of the block should be tp_basicsize.

此函数不应执行任何其他实例初始化操作,即使是分配额外内存也不应执行;那应当由 tp_new 来完成。

void (*destructor)(PyObject *)
void (*freefunc)(void *)

参见 tp_free

PyObject *(*newfunc)(PyObject *, PyObject *, PyObject *)

参见 tp_new

int (*initproc)(PyObject *, PyObject *, PyObject *)

参见 tp_init

PyObject *(*reprfunc)(PyObject *)

参见 tp_repr

PyObject *(*getattrfunc)(PyObject *self, char *attr)

返回对象的指定属性的值。

int (*setattrfunc)(PyObject *self, char *attr, PyObject *value)

为对象设置指定属性的值。 将 value 参数设为 NULL 将删除该属性。

PyObject *(*getattrofunc)(PyObject *self, PyObject *attr)

返回对象的指定属性的值。

参见 tp_getattro

int (*setattrofunc)(PyObject *self, PyObject *attr, PyObject *value)

为对象设置指定属性的值。 将 value 参数设为 NULL 将删除该属性。

参见 tp_setattro

PyObject *(*descrgetfunc)(PyObject *, PyObject *, PyObject *)

See tp_descrget.

int (*descrsetfunc)(PyObject *, PyObject *, PyObject *)

See tp_descrset.

Py_hash_t (*hashfunc)(PyObject *)

参见 tp_hash

PyObject *(*richcmpfunc)(PyObject *, PyObject *, int)

参见 tp_richcompare

PyObject *(*getiterfunc)(PyObject *)

参见 tp_iter

PyObject *(*iternextfunc)(PyObject *)

参见 tp_iternext

Py_ssize_t (*lenfunc)(PyObject *)
int (*getbufferproc)(PyObject *, Py_buffer *, int)
void (*releasebufferproc)(PyObject *, Py_buffer *)
PyObject *(*unaryfunc)(PyObject *)
PyObject *(*binaryfunc)(PyObject *, PyObject *)
PyObject *(*ternaryfunc)(PyObject *, PyObject *, PyObject *)
PyObject *(*ssizeargfunc)(PyObject *, Py_ssize_t)
int (*ssizeobjargproc)(PyObject *, Py_ssize_t)
int (*objobjproc)(PyObject *, PyObject *)
int (*objobjargproc)(PyObject *, PyObject *, PyObject *)

例子

下面是一些 Python 类型定义的简单示例。 其中包括你可能会遇到的通常用法。 有些演示了令人困惑的边际情况。 要获取更多示例、实践信息以及教程,请参阅 自定义扩展类型:教程定义扩展类型:已分类主题

A basic static type:

typedef struct {
    PyObject_HEAD
    const char *data;
} MyObject;

static PyTypeObject MyObject_Type = {
    PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "mymod.MyObject",
    .tp_basicsize = sizeof(MyObject),
    .tp_doc = PyDoc_STR("My objects"),
    .tp_new = myobj_new,
    .tp_dealloc = (destructor)myobj_dealloc,
    .tp_repr = (reprfunc)myobj_repr,
};

你可能还会看到带有更繁琐的初始化器的较旧代码(特别是在 CPython 代码库中):

static PyTypeObject MyObject_Type = {
    PyVarObject_HEAD_INIT(NULL, 0)
    "mymod.MyObject",               /* tp_name */
    sizeof(MyObject),               /* tp_basicsize */
    0,                              /* tp_itemsize */
    (destructor)myobj_dealloc,      /* tp_dealloc */
    0,                              /* tp_vectorcall_offset */
    0,                              /* tp_getattr */
    0,                              /* tp_setattr */
    0,                              /* tp_as_async */
    (reprfunc)myobj_repr,           /* tp_repr */
    0,                              /* tp_as_number */
    0,                              /* tp_as_sequence */
    0,                              /* tp_as_mapping */
    0,                              /* tp_hash */
    0,                              /* tp_call */
    0,                              /* tp_str */
    0,                              /* tp_getattro */
    0,                              /* tp_setattro */
    0,                              /* tp_as_buffer */
    0,                              /* tp_flags */
    PyDoc_STR("My objects"),        /* tp_doc */
    0,                              /* tp_traverse */
    0,                              /* tp_clear */
    0,                              /* tp_richcompare */
    0,                              /* tp_weaklistoffset */
    0,                              /* tp_iter */
    0,                              /* tp_iternext */
    0,                              /* tp_methods */
    0,                              /* tp_members */
    0,                              /* tp_getset */
    0,                              /* tp_base */
    0,                              /* tp_dict */
    0,                              /* tp_descr_get */
    0,                              /* tp_descr_set */
    0,                              /* tp_dictoffset */
    0,                              /* tp_init */
    0,                              /* tp_alloc */
    myobj_new,                      /* tp_new */
};

一个支持弱引用、实例字典和哈希运算的类型:

typedef struct {
    PyObject_HEAD
    const char *data;
    PyObject *inst_dict;
    PyObject *weakreflist;
} MyObject;

static PyTypeObject MyObject_Type = {
    PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "mymod.MyObject",
    .tp_basicsize = sizeof(MyObject),
    .tp_doc = PyDoc_STR("My objects"),
    .tp_weaklistoffset = offsetof(MyObject, weakreflist),
    .tp_dictoffset = offsetof(MyObject, inst_dict),
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
    .tp_new = myobj_new,
    .tp_traverse = (traverseproc)myobj_traverse,
    .tp_clear = (inquiry)myobj_clear,
    .tp_alloc = PyType_GenericNew,
    .tp_dealloc = (destructor)myobj_dealloc,
    .tp_repr = (reprfunc)myobj_repr,
    .tp_hash = (hashfunc)myobj_hash,
    .tp_richcompare = PyBaseObject_Type.tp_richcompare,
};

A str subclass that cannot be subclassed and cannot be called to create instances (e.g. uses a separate factory func):

typedef struct {
    PyUnicodeObject raw;
    char *extra;
} MyStr;

static PyTypeObject MyStr_Type = {
    PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "mymod.MyStr",
    .tp_basicsize = sizeof(MyStr),
    .tp_base = NULL,  // set to &PyUnicode_Type in module init
    .tp_doc = PyDoc_STR("my custom str"),
    .tp_flags = Py_TPFLAGS_DEFAULT,
    .tp_new = NULL,
    .tp_repr = (reprfunc)myobj_repr,
};

The simplest static type (with fixed-length instances):

typedef struct {
    PyObject_HEAD
} MyObject;

static PyTypeObject MyObject_Type = {
    PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "mymod.MyObject",
};

The simplest static type (with variable-length instances):

typedef struct {
    PyObject_VAR_HEAD
    const char *data[1];
} MyObject;

static PyTypeObject MyObject_Type = {
    PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "mymod.MyObject",
    .tp_basicsize = sizeof(MyObject) - sizeof(char *),
    .tp_itemsize = sizeof(char *),
};