Об’єктний протокол¶
-
PyObject *Py_NotImplemented¶
Синглтон
NotImplemented, який використовується для сигналу про те, що операція не реалізована для даної комбінації типів.
-
Py_RETURN_NOTIMPLEMENTED¶
Properly handle returning
Py_NotImplementedfrom within a C function (that is, create a new strong reference to NotImplemented and return it).
-
Py_PRINT_RAW¶
Flag to be used with multiple functions that print the object (like
PyObject_Print()andPyFile_WriteObject()). If passed, these function would use thestr()of the object instead of therepr().
-
int PyObject_Print(PyObject *o, FILE *fp, int flags)¶
Print an object o, on file fp. Returns
-1on error. The flags argument is used to enable certain printing options. The only option currently supported isPy_PRINT_RAW; if given, thestr()of the object is written instead of therepr().
-
int PyObject_HasAttr(PyObject *o, PyObject *attr_name)¶
- Part of the Stable ABI.
Returns
1if o has the attribute attr_name, and0otherwise. This is equivalent to the Python expressionhasattr(o, attr_name). This function always succeeds.Примітка
Exceptions that occur when this calls
__getattr__()and__getattribute__()methods are silently ignored. For proper error handling, usePyObject_GetAttr()instead.
-
int PyObject_HasAttrString(PyObject *o, const char *attr_name)¶
- Part of the Stable ABI.
This is the same as
PyObject_HasAttr(), but attr_name is specified as a const char* UTF-8 encoded bytes string, rather than a PyObject*.Примітка
Exceptions that occur when this calls
__getattr__()and__getattribute__()methods or while creating the temporarystrobject are silently ignored. For proper error handling, usePyObject_GetAttrString()instead.
-
PyObject *PyObject_GetAttr(PyObject *o, PyObject *attr_name)¶
- Return value: New reference. Part of the Stable ABI.
Отримати атрибут з назвою attr_name з об’єкта o. Повертає значення атрибута в разі успіху або
NULLу разі невдачі. Це еквівалент виразу Pythono.attr_name.
-
PyObject *PyObject_GetAttrString(PyObject *o, const char *attr_name)¶
- Return value: New reference. Part of the Stable ABI.
This is the same as
PyObject_GetAttr(), but attr_name is specified as a const char* UTF-8 encoded bytes string, rather than a PyObject*.
-
PyObject *PyObject_GenericGetAttr(PyObject *o, PyObject *name)¶
- Return value: New reference. Part of the Stable ABI.
Загальна функція отримання атрибутів, яка призначена для розміщення в слоті
tp_getattroоб’єкта типу. Він шукає дескриптор у словнику класів у MRO об’єкта, а також атрибут у__dict__об’єкта (якщо є). Як зазначено в Реалізація дескрипторів, дескриптори даних мають перевагу над атрибутами екземплярів, тоді як дескриптори, що не є даними, ні. В іншому випадку виникає помилкаAttributeError.
-
int PyObject_SetAttr(PyObject *o, PyObject *attr_name, PyObject *v)¶
- Part of the Stable ABI.
Установіть значення атрибута attr_name для об’єкта o на значення v. Викликати виняток і повертати
-1у разі помилки; повернути0в разі успіху. Це еквівалент оператора Pythono.attr_name = v.Якщо v має значення
NULL, атрибут видаляється. Ця поведінка застаріла на користь використанняPyObject_DelAttr(), але наразі немає планів її видалення.
-
int PyObject_SetAttrString(PyObject *o, const char *attr_name, PyObject *v)¶
- Part of the Stable ABI.
This is the same as
PyObject_SetAttr(), but attr_name is specified as a const char* UTF-8 encoded bytes string, rather than a PyObject*.Якщо v має значення
NULL, атрибут видаляється, але ця функція застаріла на користь використанняPyObject_DelAttrString().
-
int PyObject_GenericSetAttr(PyObject *o, PyObject *name, PyObject *value)¶
- Part of the Stable ABI.
Загальна функція встановлення та видалення атрибутів, яка призначена для розміщення в слоті
tp_setattroоб’єкта типу. Він шукає дескриптор даних у словнику класів у MRO об’єкта, і якщо його знайдено, він надає перевагу над налаштуванням або видаленням атрибута в словнику екземпляра. В іншому випадку атрибут встановлюється або видаляється в об’єкті__dict__(якщо є). У разі успіху повертається0, інакше виникаєAttributeErrorі повертається-1.
-
int PyObject_DelAttr(PyObject *o, PyObject *attr_name)¶
Видалити атрибут з назвою attr_name для об’єкта o. Повертає
-1у разі помилки. Це еквівалент оператора Pythondel o.attr_name.
-
int PyObject_DelAttrString(PyObject *o, const char *attr_name)¶
This is the same as
PyObject_DelAttr(), but attr_name is specified as a const char* UTF-8 encoded bytes string, rather than a PyObject*.
-
PyObject *PyObject_GenericGetDict(PyObject *o, void *context)¶
- Return value: New reference. Part of the Stable ABI since version 3.10.
Загальна реалізація засобу отримання дескриптора
__dict__. Він створює словник, якщо це необхідно.This function may also be called to get the
__dict__of the object o. PassNULLfor context when calling it. Since this function may need to allocate memory for the dictionary, it may be more efficient to callPyObject_GetAttr()when accessing an attribute on the object.On failure, returns
NULLwith an exception set.Нове в версії 3.3.
-
int PyObject_GenericSetDict(PyObject *o, PyObject *value, void *context)¶
- Part of the Stable ABI since version 3.7.
Загальна реалізація засобу налаштування дескриптора
__dict__. Ця реалізація не дозволяє видаляти словник.Нове в версії 3.3.
-
PyObject **_PyObject_GetDictPtr(PyObject *obj)¶
Return a pointer to
__dict__of the object obj. If there is no__dict__, returnNULLwithout setting an exception.This function may need to allocate memory for the dictionary, so it may be more efficient to call
PyObject_GetAttr()when accessing an attribute on the object.
-
PyObject *PyObject_RichCompare(PyObject *o1, PyObject *o2, int opid)¶
- Return value: New reference. Part of the Stable ABI.
Compare the values of o1 and o2 using the operation specified by opid, which must be one of
Py_LT,Py_LE,Py_EQ,Py_NE,Py_GT, orPy_GE, corresponding to<,<=,==,!=,>, or>=respectively. This is the equivalent of the Python expressiono1 op o2, whereopis the operator corresponding to opid. Returns the value of the comparison on success, orNULLon failure.
-
int PyObject_RichCompareBool(PyObject *o1, PyObject *o2, int opid)¶
- Part of the Stable ABI.
Compare the values of o1 and o2 using the operation specified by opid, like
PyObject_RichCompare(), but returns-1on error,0if the result is false,1otherwise.
Примітка
If o1 and o2 are the same object, PyObject_RichCompareBool()
will always return 1 for Py_EQ and 0 for Py_NE.
-
PyObject *PyObject_Format(PyObject *obj, PyObject *format_spec)¶
- Part of the Stable ABI.
Format obj using format_spec. This is equivalent to the Python expression
format(obj, format_spec).format_spec may be
NULL. In this case the call is equivalent toformat(obj). Returns the formatted string on success,NULLon failure.
-
PyObject *PyObject_Repr(PyObject *o)¶
- Return value: New reference. Part of the Stable ABI.
Обчислити рядкове представлення об’єкта o. Повертає рядкове представлення в разі успіху,
NULLу разі невдачі. Це еквівалент виразу Pythonrepr(o). Викликається вбудованою функцієюrepr().Змінено в версії 3.4: Ця функція тепер включає твердження налагодження, щоб гарантувати, що вона не відкидає мовчки активний виняток.
-
PyObject *PyObject_ASCII(PyObject *o)¶
- Return value: New reference. Part of the Stable ABI.
Як
PyObject_Repr(), обчислити рядкове представлення об’єкта o, але екранувати символи, відмінні від ASCII, у рядку, який повертаєPyObject_Repr(), за допомогою\x,\uабо\Uекранується. Це створює рядок, подібний до того, який повертаєPyObject_Repr()у Python 2. Викликається вбудованою функцієюascii().
-
PyObject *PyObject_Str(PyObject *o)¶
- Return value: New reference. Part of the Stable ABI.
Обчислити рядкове представлення об’єкта o. Повертає рядкове представлення в разі успіху,
NULLу разі невдачі. Це еквівалент виразу Pythonstr(o). Викликається вбудованою функцієюstr()і, отже, функцієюprint().Змінено в версії 3.4: Ця функція тепер включає твердження налагодження, щоб гарантувати, що вона не відкидає мовчки активний виняток.
-
PyObject *PyObject_Bytes(PyObject *o)¶
- Return value: New reference. Part of the Stable ABI.
Обчисліть байтове представлення об’єкта o. У разі помилки повертається
NULL, а в разі успіху — об’єкт bytes. Це еквівалентно виразу Pythonbytes(o), коли o не є цілим числом. На відміну відbytes(o), помилка TypeError виникає, коли o є цілим числом замість об’єкта bytes, ініціалізованого нулем.
-
int PyObject_IsSubclass(PyObject *derived, PyObject *cls)¶
- Part of the Stable ABI.
Повертає
1, якщо клас derived ідентичний або походить від класу cls, інакше повертає0. У разі помилки поверніть-1.Якщо cls є кортежем, перевірятиметься кожен запис у cls. Результатом буде
1, якщо хоча б одна з перевірок повертає1, інакше він буде0.If cls has a
__subclasscheck__()method, it will be called to determine the subclass status as described in PEP 3119. Otherwise, derived is a subclass of cls if it is a direct or indirect subclass, i.e. contained incls.__mro__.Normally only class objects, i.e. instances of
typeor a derived class, are considered classes. However, objects can override this by having a__bases__attribute (which must be a tuple of base classes).
-
int PyObject_IsInstance(PyObject *inst, PyObject *cls)¶
- Part of the Stable ABI.
Повертає
1, якщо inst є екземпляром класу cls або підкласом cls, або0, якщо ні. У разі помилки повертає-1і встановлює виняток.Якщо cls є кортежем, перевірятиметься кожен запис у cls. Результатом буде
1, якщо хоча б одна з перевірок повертає1, інакше він буде0.If cls has a
__instancecheck__()method, it will be called to determine the subclass status as described in PEP 3119. Otherwise, inst is an instance of cls if its class is a subclass of cls.An instance inst can override what is considered its class by having a
__class__attribute.An object cls can override if it is considered a class, and what its base classes are, by having a
__bases__attribute (which must be a tuple of base classes).
-
Py_hash_t PyObject_Hash(PyObject *o)¶
- Part of the Stable ABI.
Обчислити та повернути хеш-значення об’єкта o. У разі помилки поверніть
-1. Це еквівалент виразу Pythonhash(o).Змінено в версії 3.2: Тип повернення тепер Py_hash_t. Це ціле число зі знаком такого ж розміру, як
Py_ssize_t.
-
Py_hash_t PyObject_HashNotImplemented(PyObject *o)¶
- Part of the Stable ABI.
Set a
TypeErrorindicating thattype(o)is not hashable and return-1. This function receives special treatment when stored in atp_hashslot, allowing a type to explicitly indicate to the interpreter that it is not hashable.
-
int PyObject_IsTrue(PyObject *o)¶
- Part of the Stable ABI.
Повертає
1, якщо об’єкт o вважається істинним, і0в іншому випадку. Це еквівалентно виразу Pythonnot not o. У разі помилки поверніть-1.
-
int PyObject_Not(PyObject *o)¶
- Part of the Stable ABI.
Повертає
0, якщо об’єкт o вважається істинним, і1інакше. Це еквівалентно виразу Pythonnot o. У разі помилки поверніть-1.
-
PyObject *PyObject_Type(PyObject *o)¶
- Return value: New reference. Part of the Stable ABI.
When o is non-
NULL, returns a type object corresponding to the object type of object o. On failure, raisesSystemErrorand returnsNULL. This is equivalent to the Python expressiontype(o). This function creates a new strong reference to the return value. There’s really no reason to use this function instead of thePy_TYPE()function, which returns a pointer of type PyTypeObject*, except when a new strong reference is needed.
-
int PyObject_TypeCheck(PyObject *o, PyTypeObject *type)¶
Повертає відмінне від нуля значення, якщо об’єкт o має тип type або підтип type, і
0інакше. Обидва параметри не мають бутиNULL.
-
Py_ssize_t PyObject_Size(PyObject *o)¶
-
Py_ssize_t PyObject_Length(PyObject *o)¶
- Part of the Stable ABI.
Повертає довжину об’єкта o. Якщо об’єкт o надає протоколи послідовності та відображення, повертається довжина послідовності. У разі помилки повертається
-1. Це еквівалент виразу Pythonlen(o).
-
Py_ssize_t PyObject_LengthHint(PyObject *o, Py_ssize_t defaultvalue)¶
Повертає приблизну довжину об’єкта o. Спочатку спробуйте повернути його фактичну довжину, потім оцінку за допомогою
__length_hint__()і, нарешті, поверніть значення за замовчуванням. У разі помилки повертає-1. Це еквівалент виразу Pythonoperator.length_hint(o, defaultvalue).Нове в версії 3.4.
-
PyObject *PyObject_GetItem(PyObject *o, PyObject *key)¶
- Return value: New reference. Part of the Stable ABI.
Повертає елемент o, що відповідає об’єкту key або
NULLу разі помилки. Це еквівалент виразу Pythono[key].
-
int PyObject_SetItem(PyObject *o, PyObject *key, PyObject *v)¶
- Part of the Stable ABI.
Зіставте об’єкт key на значення v. Викликати виняток і повертати
-1у разі помилки; повернути0в разі успіху. Це еквівалент оператора Pythono[key] = v. Ця функція не викрадає посилання на v.
-
int PyObject_DelItem(PyObject *o, PyObject *key)¶
- Part of the Stable ABI.
Видаліть зіставлення для об’єкта key з об’єкта o. Повернути
-1у разі помилки. Це еквівалентно оператору Pythondel o[key].
-
PyObject *PyObject_Dir(PyObject *o)¶
- Return value: New reference. Part of the Stable ABI.
Це еквівалентно виразу Python
dir(o), який повертає (можливо, порожній) список рядків, відповідних для аргументу об’єкта, абоNULL, якщо була помилка. Якщо аргументNULL, це схоже наdir()Python, що повертає імена поточних локальних систем; у цьому випадку, якщо жоден кадр виконання не активний, повертаєтьсяNULL, алеPyErr_Occurred()повертатиме false.
-
PyObject *PyObject_GetIter(PyObject *o)¶
- Return value: New reference. Part of the Stable ABI.
Це еквівалентно виразу Python
iter(o). Він повертає новий ітератор для аргументу об’єкта або сам об’єкт, якщо об’єкт уже є ітератором. ВикликаєTypeErrorі повертаєNULL, якщо об’єкт не можна повторити.
-
PyObject *PyObject_GetAIter(PyObject *o)¶
- Return value: New reference. Part of the Stable ABI since version 3.10.
Це еквівалент виразу Python
aiter(o). Бере об’єктAsyncIterableі повертає для ньогоAsyncIterator. Зазвичай це новий ітератор, але якщо аргументом єAsyncIterator, він повертає сам себе. ВикликаєTypeErrorі повертаєNULL, якщо об’єкт не можна повторити.Нове в версії 3.10.