Об’єкти типу¶
-
type PyTypeObject¶
- Part of the Limited API (as an opaque struct).
Структура C об’єктів, що використовуються для опису вбудованих типів.
-
PyTypeObject PyType_Type¶
- Part of the Stable ABI.
Це об’єкт типу для об’єктів типу; це той самий об’єкт, що й
typeна рівні Python.
-
int PyType_Check(PyObject *o)¶
Повертає ненульове значення, якщо об’єкт o є об’єктом типу, включаючи екземпляри типів, похідних від об’єкта стандартного типу. Повертає 0 у всіх інших випадках. Ця функція завжди успішна.
-
int PyType_CheckExact(PyObject *o)¶
Повертає відмінне від нуля значення, якщо об’єкт o є об’єктом типу, але не підтипом об’єкта стандартного типу. Повертає 0 у всіх інших випадках. Ця функція завжди успішна.
-
unsigned int PyType_ClearCache()¶
- Part of the Stable ABI.
Очистіть внутрішній кеш пошуку. Повернути тег поточної версії.
-
unsigned long PyType_GetFlags(PyTypeObject *type)¶
- Part of the Stable ABI.
Return the
tp_flagsmember of type. This function is primarily meant for use withPy_LIMITED_API; the individual flag bits are guaranteed to be stable across Python releases, but access totp_flagsitself is not part of the limited API.Нове в версії 3.2.
Змінено в версії 3.4: Тип повернення тепер
unsigned long, а неlong.
-
void PyType_Modified(PyTypeObject *type)¶
- Part of the Stable ABI.
Визнати недійсним внутрішній кеш пошуку для типу та всіх його підтипів. Цю функцію необхідно викликати після будь-якої ручної зміни атрибутів або базових класів типу.
-
int PyType_HasFeature(PyTypeObject *o, int feature)¶
Повертає ненульове значення, якщо об’єкт типу o встановлює функцію feature. Функції типу позначаються однобітовими прапорцями.
-
int PyType_IS_GC(PyTypeObject *o)¶
Return true if the type object includes support for the cycle detector; this tests the type flag
Py_TPFLAGS_HAVE_GC.
-
int PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)¶
- Part of the Stable ABI.
Повертає true, якщо a є підтипом b.
This function only checks for actual subtypes, which means that
__subclasscheck__()is not called on b. CallPyObject_IsSubclass()to do the same check thatissubclass()would do.
-
PyObject *PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)¶
- Return value: New reference. Part of the Stable ABI.
Загальний обробник для слота
tp_allocоб’єкта типу. Використовуйте стандартний механізм виділення пам’яті Python, щоб виділити новий екземпляр та ініціалізувати весь його вміст якNULL.
-
PyObject *PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)¶
- Return value: New reference. Part of the Stable ABI.
Загальний обробник для слота
tp_newоб’єкта типу. Створіть новий екземпляр, використовуючи слот типуtp_alloc.
-
int PyType_Ready(PyTypeObject *type)¶
- Part of the Stable ABI.
Завершення об’єкта типу. Це слід викликати для всіх об’єктів типу, щоб завершити їх ініціалізацію. Ця функція відповідає за додавання успадкованих слотів від базового класу типу. Повертає
0у разі успіху або-1і встановлює виняток у випадку помилки.Примітка
If some of the base classes implements the GC protocol and the provided type does not include the
Py_TPFLAGS_HAVE_GCin its flags, then the GC protocol will be automatically implemented from its parents. On the contrary, if the type being created does includePy_TPFLAGS_HAVE_GCin its flags then it must implement the GC protocol itself by at least implementing thetp_traversehandle.
-
PyObject *PyType_GetName(PyTypeObject *type)¶
- Return value: New reference. Part of the Stable ABI since version 3.11.
Return the type’s name. Equivalent to getting the type’s
__name__attribute.Нове в версії 3.11.
-
PyObject *PyType_GetQualName(PyTypeObject *type)¶
- Return value: New reference. Part of the Stable ABI since version 3.11.
Return the type’s qualified name. Equivalent to getting the type’s
__qualname__attribute.Нове в версії 3.11.
-
void *PyType_GetSlot(PyTypeObject *type, int slot)¶
- Part of the Stable ABI since version 3.4.
Повертає вказівник функції, що зберігається у вказаному слоті. Якщо результат
NULL, це означає, що або слот маєNULL, або що функцію було викликано з недійсними параметрами. Викликачі зазвичай перетворюють покажчик результату на відповідний тип функції.Перегляньте
PyType_Slot.slot, щоб дізнатися про можливі значення аргументу slot.Нове в версії 3.4.
Змінено в версії 3.10:
PyType_GetSlot()тепер може приймати всі типи. Раніше це було обмежено типами купи.
-
PyObject *PyType_GetModule(PyTypeObject *type)¶
- Part of the Stable ABI since version 3.10.
Повертає об’єкт модуля, пов’язаний із заданим типом, коли тип було створено за допомогою
PyType_FromModuleAndSpec().Якщо жоден модуль не пов’язаний із заданим типом, встановлюється
TypeErrorі повертаєтьсяNULL.This function is usually used to get the module in which a method is defined. Note that in such a method,
PyType_GetModule(Py_TYPE(self))may not return the intended result.Py_TYPE(self)may be a subclass of the intended class, and subclasses are not necessarily defined in the same module as their superclass. SeePyCMethodto get the class that defines the method. SeePyType_GetModuleByDef()for cases whenPyCMethodcannot be used.Нове в версії 3.9.
-
void *PyType_GetModuleState(PyTypeObject *type)¶
- Part of the Stable ABI since version 3.10.
Повертає стан об’єкта модуля, пов’язаного з заданим типом. Це ярлик для виклику
PyModule_GetState()за результатомPyType_GetModule().Якщо жоден модуль не пов’язаний із заданим типом, встановлюється
TypeErrorі повертаєтьсяNULL.Якщо тип має пов’язаний модуль, але його стан
NULL, повертаєNULLбез встановлення винятку.Нове в версії 3.9.
-
PyObject *PyType_GetModuleByDef(PyTypeObject *type, struct PyModuleDef *def)¶
Find the first superclass whose module was created from the given
PyModuleDefdef, and return that module.If no module is found, raises a
TypeErrorand returnsNULL.This function is intended to be used together with
PyModule_GetState()to get module state from slot methods (such astp_initornb_add) and other places where a method’s defining class cannot be passed using thePyCMethodcalling convention.Нове в версії 3.11.
Створення типів, виділених у купі¶
Наступні функції та структури використовуються для створення типів купи.
-
PyObject *PyType_FromModuleAndSpec(PyObject *module, PyType_Spec *spec, PyObject *bases)¶
- Return value: New reference. Part of the Stable ABI since version 3.10.
Creates and returns a heap type from the spec (
Py_TPFLAGS_HEAPTYPE).Аргумент bases можна використовувати для визначення базових класів; це може бути лише один клас або кортеж класів. Якщо bases має значення
NULL, замість нього використовується слот Py_tp_bases. Якщо це такожNULL, замість нього використовується слот Py_tp_base. Якщо це такожNULL, новий тип походить відobject.Аргумент module можна використовувати для запису модуля, в якому визначено новий клас. Це має бути об’єкт модуля або
NULL. Якщо неNULL, модуль асоціюється з новим типом і може бути пізніше отриманий за допомогоюPyType_GetModule(). Асоційований модуль не успадковується підкласами; її необхідно вказувати для кожного класу окремо.Ця функція викликає
PyType_Ready()для нового типу.Нове в версії 3.9.
Змінено в версії 3.10: Тепер функція приймає один клас як аргумент bases і
NULLяк слотtp_doc.
-
PyObject *PyType_FromSpecWithBases(PyType_Spec *spec, PyObject *bases)¶
- Return value: New reference. Part of the Stable ABI since version 3.3.
Equivalent to
PyType_FromModuleAndSpec(NULL, spec, bases).Нове в версії 3.3.
-
PyObject *PyType_FromSpec(PyType_Spec *spec)¶
- Return value: New reference. Part of the Stable ABI.
Equivalent to
PyType_FromSpecWithBases(spec, NULL).
-
type PyType_Spec¶
- Part of the Stable ABI (including all members).
Структура, що визначає поведінку типу.
-
const char *PyType_Spec.name¶
Назва типу, що використовується для встановлення
PyTypeObject.tp_name.
-
int PyType_Spec.basicsize¶
-
int PyType_Spec.itemsize¶
Size of the instance in bytes, used to set
PyTypeObject.tp_basicsizeandPyTypeObject.tp_itemsize.
-
int PyType_Spec.flags¶
Прапорці типу, які використовуються для встановлення
PyTypeObject.tp_flags.Якщо прапор
Py_TPFLAGS_HEAPTYPEне встановлено,PyType_FromSpecWithBases()встановлює його автоматично.
-
PyType_Slot *PyType_Spec.slots¶
Масив структур
PyType_Slot. Закінчується спеціальним значенням слота{0, NULL}.
-
const char *PyType_Spec.name¶
-
type PyType_Slot¶
- Part of the Stable ABI (including all members).
Структура, що визначає необов’язкову функціональність типу, що містить ідентифікатор слота та покажчик значення.
-
int PyType_Slot.slot¶
Ідентифікатор слота.
Ідентифікатори слотів називаються як імена полів структур
PyTypeObject,PyNumberMethods,PySequenceMethods,PyMappingMethodsіPyAsyncMethodsз доданим префіксомPy_. Наприклад, використовуйте:Py_tp_deallocдля встановленняPyTypeObject.tp_deallocPy_nb_addдля встановленняPyNumberMethods.nb_addPy_sq_lengthдля встановленняPySequenceMethods.sq_length
The following fields cannot be set at all using
PyType_SpecandPyType_Slot:tp_weaklistoffset(see PyMemberDef)tp_dictoffset(see PyMemberDef)
Setting
Py_tp_basesorPy_tp_basemay be problematic on some platforms. To avoid issues, use the bases argument ofPyType_FromSpecWithBases()instead.Змінено в версії 3.9: Слоти в
PyBufferProcsможна встановити в необмеженому API.Змінено в версії 3.11:
bf_getbufferandbf_releasebufferare now available under the limited API.
-
void *PyType_Slot.pfunc¶
Бажане значення слота. У більшості випадків це вказівник на функцію.
Слоти, окрім
Py_tp_doc, не можуть бутиNULL.
-
int PyType_Slot.slot¶