创新互联Python教程:类型对象

类型对象

Perhaps one of the most important structures of the python object system is the structure that defines a new type: the PyTypeObject structure. Type objects can be handled using any of the PyObject_* or PyType_* functions, but do not offer much that’s interesting to most Python applications. These objects are fundamental to how objects behave, so they are very important to the interpreter itself and to any extension module that implements new types.

为玉田等地区用户提供了全套网页设计制作服务,及玉田网站建设行业解决方案。主营业务为成都网站制作、成都网站建设、外贸营销网站建设、玉田网站设计,以传统方式定制建设网站,并提供域名空间备案等一条龙服务,秉承以专业、用心的态度为用户提供真诚的服务。我们深信只要达到每一位用户的要求,就会得到认可,从而选择与我们长期合作。这样,我们也可以走得更远!

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

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

快速参考

“tp_方法槽”

PyTypeObject 槽 1

Type

特殊方法/属性

信息 2

O

T

D

I

tpname

const char

name

X

X

tpbasicsize

Pyssizet

X

X

X

tpitemsize

Pyssizet

X

X

tpdealloc

destructor

X

X

X

tpvectorcall_offset

Py_ssize_t

X

X

(tp_getattr)

getattrfunc

__getattribute, __getattr

G

(tp_setattr)

setattrfunc

__setattr, __delattr

G

tp_as_async

PyAsyncMethods

子方法槽(方法域)

%

tprepr

reprfunc

repr

X

X

X

tpasnumber

PyNumberMethods

子方法槽(方法域)

%

tp_as_sequence

PySequenceMethods

子方法槽(方法域)

%

tpasmapping

PyMappingMethods

子方法槽(方法域)

%

tphash

hashfunc

hash

X

G

tpcall

ternaryfunc

call

X

X

tpstr

reprfunc

str

X

X

tpgetattro

getattrofunc

getattribute, getattr

X

X

G

tp_setattro

setattrofunc

__setattr, __delattr

X

X

G

tp_as_buffer

PyBufferProcs

%

tpflags

unsigned long

X

X

?

tpdoc

const char

doc

X

X

tptraverse

traverseproc

X

G

tpclear

inquiry

X

G

tprichcompare

richcmpfunc

lt, le, eq, ne, gt, ge

X

G

tpweaklistoffset

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

tpdict

PyObject *

dict

?

tpdescrget

descrgetfunc

get

X

tpdescrset

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

PyObject *

__bases

~

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

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

2

列:

“O”: PyBaseObject_Type 必须设置

“T”: PyType_Type 必须设置

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

 
 
 
 
  1. X - PyType_Ready sets this value if it is NULL
  2. ~ - PyType_Ready always sets this value (it should be NULL)
  3. ? - PyType_Ready may set this value depending on other slots
  4. Also see the inheritance column ("I").

“I”: 继承

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

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

子方法槽(方法域)

方法槽

Type

特殊方法

amawait

unaryfunc

await

amaiter

unaryfunc

aiter

amanext

unaryfunc

anext

amsend

sendfunc

nbadd

binaryfunc

add radd

nbinplaceadd

binaryfunc

iadd

nbsubtract

binaryfunc

sub rsub

nbinplacesubtract

binaryfunc

isub

nbmultiply

binaryfunc

mul rmul

nbinplacemultiply

binaryfunc

imul

nbremainder

binaryfunc

mod rmod

nbinplaceremainder

binaryfunc

imod

nbdivmod

binaryfunc

divmod rdivmod

nbpower

ternaryfunc

pow rpow

nbinplacepower

ternaryfunc

ipow

nbnegative

unaryfunc

neg

nbpositive

unaryfunc

pos

nbabsolute

unaryfunc

abs

nbbool

inquiry

bool

nbinvert

unaryfunc

invert

nblshift

binaryfunc

lshift rlshift

nbinplacelshift

binaryfunc

ilshift

nbrshift

binaryfunc

rshift rrshift

nbinplacershift

binaryfunc

irshift

nband

binaryfunc

and rand

nbinplaceand

binaryfunc

iand

nbxor

binaryfunc

xor rxor

nbinplacexor

binaryfunc

ixor

nbor

binaryfunc

or ror

nbinplaceor

binaryfunc

ior

nbint

unaryfunc

int

nbreserved

void *

nbfloat

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

PyTypeObject Py_ssize_t

PyObject

destructor

void

void

freefunc

void

void

traverseproc

void visitproc void

int

newfunc

PyObject PyObject PyObject

PyObject

initproc

PyObject PyObject PyObject

int

reprfunc

PyObject

PyObject

getattrfunc

PyObject const char

PyObject

setattrfunc

PyObject const char PyObject

int

getattrofunc

PyObject PyObject

PyObject

setattrofunc

PyObject PyObject PyObject

int

descrgetfunc

PyObject PyObject PyObject

PyObject

descrsetfunc

PyObject PyObject PyObject

int

hashfunc

PyObject

Py_hash_t

richcmpfunc

PyObject PyObject int

PyObject

getiterfunc

PyObject

PyObject

iternextfunc

PyObject

PyObject

lenfunc

PyObject

Py_ssize_t

getbufferproc

PyObject Py_buffer int

int

releasebufferproc

PyObject Py_buffer

void

inquiry

void

int

unaryfunc

PyObject

PyObject

binaryfunc

PyObject PyObject

PyObject

ternaryfunc

PyObject PyObject PyObject

PyObject

ssizeargfunc

PyObject Py_ssize_t

PyObject

ssizeobjargproc

PyObject Py_ssize_t

int

objobjproc

PyObject PyObject

int

objobjargproc

PyObject PyObject PyObject *

int

请参阅 Slot Type typedefs 里有更多详细信息。

PyTypeObject 定义

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

 
 
 
 
  1. typedef struct _typeobject {
  2. PyObject_VAR_HEAD
  3. const char *tp_name; /* For printing, in format "." */
  4. Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */
  5. /* Methods to implement standard operations */
  6. destructor tp_dealloc;
  7. Py_ssize_t tp_vectorcall_offset;
  8. getattrfunc tp_getattr;
  9. setattrfunc tp_setattr;
  10. PyAsyncMethods *tp_as_async; /* formerly known as tp_compare (Python 2)
  11. or tp_reserved (Python 3) */
  12. reprfunc tp_repr;
  13. /* Method suites for standard classes */
  14. PyNumberMethods *tp_as_number;
  15. PySequenceMethods *tp_as_sequence;
  16. PyMappingMethods *tp_as_mapping;
  17. /* More standard operations (here for binary compatibility) */
  18. hashfunc tp_hash;
  19. ternaryfunc tp_call;
  20. reprfunc tp_str;
  21. getattrofunc tp_getattro;
  22. setattrofunc tp_setattro;
  23. /* Functions to access object as input/output buffer */
  24. PyBufferProcs *tp_as_buffer;
  25. /* Flags to define presence of optional/expanded features */
  26. unsigned long tp_flags;
  27. const char *tp_doc; /* Documentation string */
  28. /* Assigned meaning in release 2.0 */
  29. /* call function for all accessible objects */
  30. traverseproc tp_traverse;
  31. /* delete references to contained objects */
  32. inquiry tp_clear;
  33. /* Assigned meaning in release 2.1 */
  34. /* rich comparisons */
  35. richcmpfunc tp_richcompare;
  36. /* weak reference enabler */
  37. Py_ssize_t tp_weaklistoffset;
  38. /* Iterators */
  39. getiterfunc tp_iter;
  40. iternextfunc tp_iternext;
  41. /* Attribute descriptor and subclassing stuff */
  42. struct PyMethodDef *tp_methods;
  43. struct PyMemberDef *tp_members;
  44. struct PyGetSetDef *tp_getset;
  45. // Strong reference on a heap type, borrowed reference on a static type
  46. struct _typeobject *tp_base;
  47. PyObject *tp_dict;
  48. descrgetfunc tp_descr_get;
  49. descrsetfunc tp_descr_set;
  50. Py_ssize_t tp_dictoffset;
  51. initproc tp_init;
  52. allocfunc tp_alloc;
  53. newfunc tp_new;
  54. freefunc tp_free; /* Low-level free-memory routine */
  55. inquiry tp_is_gc; /* For PyObject_IS_GC */
  56. PyObject *tp_bases;
  57. PyObject *tp_mro; /* method resolution order */
  58. PyObject *tp_cache;
  59. PyObject *tp_subclasses;
  60. PyObject *tp_weaklist;
  61. destructor tp_del;
  62. /* Type attribute cache version tag. Added in version 2.6 */
  63. unsigned int tp_version_tag;
  64. destructor tp_finalize;
  65. vectorcallfunc tp_vectorcall;
  66. } PyTypeObject;

PyObject 槽位

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

Py_ssize_t PyObject.ob_refcnt

Part of the Stable ABI.

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

继承:

子类型不继承此字段。

PyTypeObject *PyObject.ob_type

Part of the Stable ABI.

This is the type’s type, in other words its metatype. It is initialized by the argument to the PyObject_HEAD_INIT macro, and its value should normally be &PyType_Type. However, for dynamically loadable extension modules that must be usable on Windows (at least), the compiler complains that this is not a valid initializer. Therefore, the convention is to pass NULL to the PyObject_HEAD_INIT macro and to initialize this field explicitly at the start of the module’s initialization function, before doing anything else. This is typically done like this:

 
 
 
 
  1. Foo_Type.ob_type = &PyType_Type;

This should be done before any instances of the type are created. PyType_Ready() checks if ob_type is NULL, and if so, initializes it to the ob_type field of the base class. PyType_Ready() will not change this field if it is non-zero.

继承:

此字段会被子类型继承。

PyObject *PyObject._ob_next

PyObject *PyObject._ob_prev

These fields are only present when the macro Py_TRACE_REFS is defined (see the configure —with-trace-refs option).

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 uses are the sys.getobjects() function and to print the objects that are still alive at the end of a run when the environment variable PYTHONDUMPREFS is set.

继承:

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

PyVarObject 槽位

Py_ssize_t PyVarObject.ob_size

Part of the Stable ABI.

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

继承:

子类型不继承此字段。

PyTypeObject 槽

Each slot has a section describing inheritance. If PyType_Ready() may set a value when the field is set to NULL then there will also be a “Default” section. (Note that many fields set on PyBaseObject_Type and PyType_Type effectively act as defaults.)

const char *PyTypeObject.tp_name

Pointer to a NUL-terminated string containing the name of the type. For types that are accessible as module globals, the string should be the full module name, followed by a dot, followed by the type name; for built-in types, it should be just the type name. If the module is a submodule of a package, the full package name is part of the full module name. For example, a type named T defined in module M in subpackage Q in package P should have the tp_name initializer "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.

If no dot is present, the entire tp_name field is made accessible as the __name__ attribute, and the __module__ attribute is undefined (unless explicitly set in the dictionary, as explained above). This means your type will be impossible to pickle. Additionally, it will not be listed in module documentations created with pydoc.

This field must not be NULL. It is the only required field in PyTypeObject() (other than potentially tp_itemsize).

继承:

子类型不继承此字段。

Py_ssize_t PyTypeObject.tp_basicsize

Py_ssize_t PyTypeObject.tp_itemsize

These fields allow calculating the size in bytes of instances of the type.

There are two kinds of types: types with fixed-length instances have a zero tp_itemsize field, types with variable-length instances have a non-zero tp_itemsize field. For a type with fixed-length instances, all instances have the same size, given in 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.

A note about alignment: if the variable items require a particular alignment, this should be taken care of by the value of tp_basicsize. Example: suppose a type implements an array of double. tp_itemsize is sizeof(double). It is the programmer’s responsibility that tp_basicsize is a multiple of sizeof(double) (assuming this is the alignment requirement for double).

For any type with variable-length instances, this field must not be NULL.

继承:

These fields are inherited separately by subtypes. If the base type has a non-zero tp_itemsize, it is generally not safe to set tp_itemsize to a different non-zero value in a subtype (though this depends on the implementation of the base type).

destructor PyTypeObject.tp_dealloc

A pointer to the instance destructor function. This function must be defined unless the type guarantees that its instances will never be deallocated (as is the case for the singletons None and Ellipsis). The function signature is:

 
 
 
 
  1. void tp_dealloc(PyObject *self);

The destructor function is called by the Py_DECREF() and Py_XDECREF() macros when the new reference count is zero. At this point, the instance is still in existence, but there are no references to it. The destructor function should free all references which the instance owns, free all memory buffers owned by the instance (using the freeing function corresponding to the allocation function used to allocate the buffer), and call the type’s tp_free function. If the type is not subtypable (doesn’t have the Py_TPFLAGS_BASETYPE flag bit set), it is permissible to call the object deallocator directly instead of via tp_free. The object deallocator should be the one used to allocate the instance; this is normally PyObject_Del() if the instance was allocated using PyObject_New() or PyObject_VarNew(), or PyObject_GC_Del() if the instance was allocated using PyObject_GC_New() or PyObject_GC_NewVar().

If the type supports garbage collection (has the Py_TPFLAGS_HAVE_GC flag bit set), the destructor should call PyObject_GC_UnTrack() before clearing any member fields.

 
 
 
 
  1. static void foo_dealloc(foo_object *self) {
  2. PyObject_GC_UnTrack(self);
  3. Py_CLEAR(self->ref);
  4. Py_TYPE(self)->tp_free((PyObject *)self);
  5. }

Finally, if the type is heap allocated (Py_TPFLAGS_HEAPTYPE), the deallocator should decrement the reference count for its type object after calling the type deallocator. In order to avoid dangling pointers, the recommended way to achieve this is:

 
 
 
 
  1. static void foo_dealloc(foo_object *self) {
  2. PyTypeObject *tp = Py_TYPE(self);
  3. // free references and buffers here
  4. tp->tp_free(self);
  5. Py_DECREF(tp);
  6. }

继承:

此字段会被子类型继承。

Py_ssize_t PyTypeObject.tp_vectorcall_offset

An optional offset to a per-instance function that implements calling the object using the vectorcall protocol, a more efficient alternative of the simpler 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.

Any class that sets Py_TPFLAGS_HAVE_VECTORCALL must also set tp_call and make sure its behaviour is consistent with the vectorcallfunc function. This can be done by setting tp_call to PyVectorcall_Call().

警告

It is not recommended for mutable 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.

在 3.8 版更改: Before version 3.8, this slot was named tp_print. In Python 2.x, it was used for printing to a file. In Python 3.0 to 3.7, it was unused.

继承:

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 types without the Py_TPFLAGS_IMMUTABLETYPE flag set (including subclasses defined in Python).

getattrfunc PyTypeObject.tp_getattr

An optional pointer to the get-attribute-string function.

This field is deprecated. When it is defined, it should point to a function that acts the same as the tp_getattro function, but taking a C string instead of a Python string object to give the attribute name.

继承:

分组: tp_getattr, tp_getattro

This field is inherited by subtypes together with tp_getattro: a subtype inherits both tp_getattr and tp_getattro from its base type when the subtype’s tp_getattr and tp_getattro are both NULL.

setattrfunc PyTypeObject.tp_setattr

An optional pointer to the function for setting and deleting attributes.

This field is deprecated. When it is defined, it should point to a function that acts the same as the tp_setattro function, but taking a C string instead of a Python string object to give the attribute name.

继承:

Group: tp_setattr, tp_setattro

This field is inherited by subtypes together with tp_setattro: a subtype inherits both tp_setattr and tp_setattro from its base type when the subtype’s tp_setattr and tp_setattro are both NULL.

PyAsyncMethods *PyTypeObject.tp_as_async

Pointer to an additional structure that contains fields relevant only to objects which implement awaitable and asynchronous iterator protocols at the C-level. See Async Object Structures for details.

3.5 新版功能: Formerly known as tp_compare and tp_reserved.

继承:

The tp_as_async field is not inherited, but the contained fields are inherited individually.

reprfunc PyTypeObject.tp_repr

An optional pointer to a function that implements the built-in function repr().

The signature is the same as for PyObject_Repr():

 
 
 
 
  1. PyObject *tp_repr(PyObject *self);

The function must return a string or a Unicode object. Ideally, this function should return a string that, when passed to eval(), given a suitable environment, returns an object with the same value. If this is not feasible, it should return a string starting with '<' and ending with '>' from which both the type and the value of the object can be deduced.

继承:

此字段会被子类型继承。

默认:

When this field is not set, a string of the form <%s object at %p> is returned, where %s is replaced by the type name, and %p by the object’s memory address.

PyNumberMethods *PyTypeObject.tp_as_number

Pointer to an additional structure that contains fields relevant only to objects which implement the number protocol. These fields are documented in Number Object Structures.

继承:

The tp_as_number field is not inherited, but the contained fields are inherited individually.

PySequenceMethods *PyTypeObject.tp_as_sequence

Pointer to an additional structure that contains fields relevant only to objects which implement the sequence protocol. These fields are documented in Sequence Object Structures.

继承:

The tp_as_sequence field is not inherited, but the contained fields are inherited individually.

PyMappingMethods *PyTypeObject.tp_as_mapping

Pointer to an additional structure that contains fields relevant only to objects which implement the mapping protocol. These fields are documented in Mapping Object Structures.

继承:

The tp_as_mapping field is not inherited, but the contained fields are inherited individually.

hashfunc PyTypeObject.tp_hash

An optional pointer to a function that implements the built-in function hash().

The signature is the same as for PyObject_Hash():

 
 
 
 
  1. Py_hash_t tp_hash(PyObject *);

The value -1 should not be returned as a normal return value; when an error occurs during the computation of the hash value, the function should set an exception and return -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().

This field can be set explicitly to PyObject_HashNotImplemented() to block inheritance of the hash method from a parent type. This is interpreted as the equivalent of __hash__ = None at the Python level, causing isinstance(o, collections.Hashable) to correctly return False. Note that the converse is also true - setting __hash__ = None on a class at the Python level will result in the tp_hash slot being set to PyObject_HashNotImplemented().

继承:

Group: tp_hash, tp_richcompare

This field is inherited by subtypes together with tp_richcompare: a subtype inherits both of tp_richcompare and tp_hash, when the subtype’s tp_richcompare and tp_hash are both NULL.

ternaryfunc PyTypeObject.tp_call

An optional pointer to a function that implements calling the object. This should be NULL if the object is not callable. The signature is the same as for PyObject_Call():

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

继承:

此字段会被子类型继承。

reprfunc PyTypeObject.tp_str

An optional pointer to a function that implements the built-in operation str(). (Note that str is a type now, and str() calls the constructor for that type. This constructor calls PyObject_Str() to do the actual work, and PyObject_Str() will call this handler.)

The signature is the same as for PyObject_Str():

 
 
 
 
  1. PyObject *tp_str(PyObject *self);

The function must return a string or a Unicode object. It should be a “friendly” string representation of the object, as this is the representation that will be used, among other things, by the print() function.

继承:

此字段会被子类型继承。

默认:

When this field is not set, PyObject_Repr() is called to return a string representation.

getattrofunc PyTypeObject.tp_getattro

An optional pointer to the get-attribute function.

The signature is the same as for PyObject_GetAttr():

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

It is usually convenient to set this field to PyObject_GenericGetAttr(), which implements the normal way of looking for object attributes.

继承:

分组: tp_getattr, tp_getattro

This field is inherited by subtypes together with tp_getattr: a subtype inherits both tp_getattr and tp_getattro from its base type when the subtype’s tp_getattr and tp_getattro are both NULL.

默认:

PyBaseObject_Type uses PyObject_GenericGetAttr().

setattrofunc PyTypeObject.tp_setattro

An optional pointer to the function for setting and deleting attributes.

The signature is the same as for PyObject_SetAttr():

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

In addition, setting value to NULL to delete an attribute must be supported. It is usually convenient to set this field to PyObject_GenericSetAttr(), which implements the normal way of setting object attributes.

继承:

Group: tp_setattr, tp_setattro

This field is inherited by subtypes together with tp_setattr: a subtype inherits both tp_setattr and tp_setattro from its base type when the subtype’s tp_setattr and tp_setattro are both NULL.

默认:

PyBaseObject_Type 使用 PyObject_GenericSetAttr().

PyBufferProcs *PyTypeObject.tp_as_buffer

Pointer to an additional structure that contains fields relevant only to objects which implement the buffer interface. These fields are documented in Buffer Object Structures.

继承:

The tp_as_buffer field is not inherited, but the contained fields are inherited individually.

unsigned long PyTypeObject.tp_flags

This field is a bit mask of various flags. Some flags indicate variant semantics for certain situations; others are used to indicate that certain fields in the type object (or in the extension structures referenced via tp_as_number, tp_as_sequence, tp_as_mapping, and tp_as_buffer) that were historically not always present are valid; if such a flag bit is clear, the type fields it guards must not be accessed and must be considered to have a zero or NULL value instead.

继承:

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.

Bit Masks:

The following bit masks are currently defined; these can be ORed together using the | operator to form the value of the tp_flags field. The macro PyType_HasFeature() takes a type and a flags value, tp and f, and checks whether tp->tp_flags & f is non-zero.

  • 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

    This bit is set when the type can be used as the base type of another type. If this bit is clear, the type cannot be subtyped (similar to a “final” class in Java).

    继承:

    ???

  • Py_TPFLAGS_READY

    This bit is set when the type object has been fully initialized by PyType_Ready().

    继承:

    ???

  • Py_TPFLAGS_READYING

    This bit is set while PyType_Ready() is in the process of initializing the type object.

    继承:

    ???

  • Py_TPFLAGS_HAVE_GC

    This bit is set when the object supports garbage collection. If this bit is set, instances must be created using PyObject_GC_New() and destroyed using PyObject_GC_Del(). More information in section 使对象类型支持循环垃圾回收. This bit also implies that the GC-related fields tp_traverse and tp_clear are present in the type object.

    继承:

    Group: 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_METHOD_DESCRIPTOR

    This bit indicates that objects behave like unbound methods.

    If this flag is set for type(meth), then:

    • meth.__get__(obj, cls)(*args, **kwds) (with obj not None) must be equivalent to meth(obj, *args, **kwds).

    • meth.__get__(None, cls)(*args, **kwds) must be equivalent to meth(*args, **kwds).

    This flag enables an optimization for typical method calls like obj.meth(): it avoids creating a temporary “bound method” object for obj.meth.

    3.8 新版功能.

    继承:

    This flag is never inherited by types without the Py_TPFLAGS_IMMUTABLETYPE flag set. 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

    These flags are used by functions such as PyLong_Check() to quickly determine if a type is a subclass of a built-in type; such specific checks are faster than a generic check, like PyObject_IsInstance(). Custom types that inherit from built-ins should have their tp_flags set appropriately, or the code that interacts with such types will behave differently depending on what kind of check is used.

  • Py_TPFLAGS_HAVE_FINALIZE

    This bit is set when the tp_finalize slot is present in the type structure.

    3.4 新版功能.

    3.8 版后已移除: This flag isn’t necessary anymore, as the interpreter assumes the tp_finalize slot is always present in the type structure.

  • Py_TPFLAGS_HAVE_VECTORCALL

    This bit is set when the class implements the vectorcall protocol. See tp_vectorcall_offset for details.

    继承:

    This bit is inherited for types with the Py_TPFLAGS_IMMUTABLETYPE flag set, if tp_call is also inherited.

    3.9 新版功能.

  • Py_TPFLAGS_IMMUTABLETYPE

    This bit is set for type objects that are immutable: type attributes cannot be set nor deleted.

    PyType_Ready() automatically applies this flag to static types.

    继承:

    This flag is not inherited.

    3.10 新版功能.

  • Py_TPFLAGS_DISALLOW_INSTANTIATION

    Disallow creating instances of the type: set tp_new to NULL and don’t create the __new__ key in the type dictionary.

    The flag must be set before creating the type, not after. For example, it must be set before PyType_Ready() is called on the type.

    The flag is set automatically on static types if tp_base is NULL or &PyBaseObject_Type and tp_new is NULL.

    继承:

    This flag is not inherited. However, subclasses will not be instantiable unless they provide a non-NULL tp_new (which is only possible via the C API).

    备注

    To disallow instantiating a class directly but allow instantiating its subclasses (e.g. for an abstract base class), do not use this flag. Instead, make tp_new only succeed for subclasses.

    3.10 新版功能.

  • Py_TPFLAGS_MAPPING

    This bit indicates that instances of the class may match mapping patterns when used as the subject of a match block. It is automatically set when registering or subclassing collections.abc.Mapping, and unset when registering collections.abc.Sequence.

    备注

    Py_TPFLAGS_MAPPING and Py_TPFLAGS_SEQUENCE are mutually exclusive; it is an error to enable both flags simultaneously.

    继承:

    This flag is inherited by types that do not already set Py_TPFLAGS_SEQUENCE.

    参见

    PEP 634 —— 结构化模式匹配:规范

    3.10 新版功能.

  • Py_TPFLAGS_SEQUENCE

    This bit indicates that instances of the class may match sequence patterns when used as the subject of a match block. It is automatically set when registering or subclassing collections.abc.Sequence, and unset when registering collections.abc.Mapping.

    备注

    Py_TPFLAGS_MAPPING and Py_TPFLAGS_SEQUENCE are mutually exclusive; it is an error to enable both flags simultaneously.

    继承:

    This flag is inherited by types that do not already set Py_TPFLAGS_MAPPING.

    参见

    PEP 634 —— 结构化模式匹配:规范

    3.10 新版功能.

const char *PyTypeObject.tp_doc

An optional pointer to a NUL-terminated C string giving the docstring for this type object. This is exposed as the __doc__ attribute on the type and instances of the type.

继承:

This field is not inherited by subtypes.

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:

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

More information about Python’s garbage collection scheme can be found in section 使对象类型支持循环垃圾回收.

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:

 
 
 
 
  1. static int
  2. local_traverse(localobject *self, visitproc visit, void *arg)
  3. {
  4. Py_VISIT(self->args);
  5. Py_VISIT(self->kw);
  6. Py_VISIT(self->dict);
  7. return 0;
  8. }

Note that Py_VISIT() is called only on those members that can participate in reference cycles. Although there is also a self->key member, it can only be NULL or a Python string and therefore cannot be part of a reference cycle.

On the other hand, even if you know a member can never be part of a cycle, as a debugging aid you may want to visit it anyway just so the gc module’s get_referents() function will include it.

警告

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).

Note that Py_VISIT() requires the visit and arg parameters to local_traverse() to have these specific names; don’t name them just anything.

I

分享文章:创新互联Python教程:类型对象
分享路径:http://www.shufengxianlan.com/qtweb/news25/88325.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联