# Copyright (C) 2001-2020, Python Software Foundation # This file is distributed under the same license as the Python package. # Maintained by the python-doc-es workteam. # docs-es@python.org / # https://mail.python.org/mailman3/lists/docs-es.python.org/ # Check https://github.com/python/python-docs-es/blob/3.8/TRANSLATORS to # get the list of volunteers # msgid "" msgstr "" "Project-Id-Version: Python 3.8\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2024-11-21 16:38-0300\n" "PO-Revision-Date: 2021-10-19 20:28-0500\n" "Last-Translator: Cristián Maureira-Fredes \n" "Language: es\n" "Language-Team: python-doc-es\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" "Generated-By: Babel 2.16.0\n" #: ../Doc/extending/newtypes.rst:7 msgid "Defining Extension Types: Assorted Topics" msgstr "Definición de tipos de extensión: temas variados" #: ../Doc/extending/newtypes.rst:11 msgid "" "This section aims to give a quick fly-by on the various type methods you can " "implement and what they do." msgstr "" "Esta sección tiene como objetivo dar un vistazo rápido a los diversos " "métodos de tipo que puede implementar y lo que hacen." #: ../Doc/extending/newtypes.rst:14 msgid "" "Here is the definition of :c:type:`PyTypeObject`, with some fields only used " "in :ref:`debug builds ` omitted:" msgstr "" "Aquí está la definición de :c:type:`PyTypeObject`, con algunos campos que " "solo se usan en las :ref:`versiones de depuración ` omitidas:" #: ../Doc/extending/newtypes.rst:17 msgid "" "typedef struct _typeobject {\n" " PyObject_VAR_HEAD\n" " const char *tp_name; /* For printing, in format \".\" */\n" " Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */\n" "\n" " /* Methods to implement standard operations */\n" "\n" " destructor tp_dealloc;\n" " Py_ssize_t tp_vectorcall_offset;\n" " getattrfunc tp_getattr;\n" " setattrfunc tp_setattr;\n" " PyAsyncMethods *tp_as_async; /* formerly known as tp_compare (Python 2)\n" " or tp_reserved (Python 3) */\n" " reprfunc tp_repr;\n" "\n" " /* Method suites for standard classes */\n" "\n" " PyNumberMethods *tp_as_number;\n" " PySequenceMethods *tp_as_sequence;\n" " PyMappingMethods *tp_as_mapping;\n" "\n" " /* More standard operations (here for binary compatibility) */\n" "\n" " hashfunc tp_hash;\n" " ternaryfunc tp_call;\n" " reprfunc tp_str;\n" " getattrofunc tp_getattro;\n" " setattrofunc tp_setattro;\n" "\n" " /* Functions to access object as input/output buffer */\n" " PyBufferProcs *tp_as_buffer;\n" "\n" " /* Flags to define presence of optional/expanded features */\n" " unsigned long tp_flags;\n" "\n" " const char *tp_doc; /* Documentation string */\n" "\n" " /* Assigned meaning in release 2.0 */\n" " /* call function for all accessible objects */\n" " traverseproc tp_traverse;\n" "\n" " /* delete references to contained objects */\n" " inquiry tp_clear;\n" "\n" " /* Assigned meaning in release 2.1 */\n" " /* rich comparisons */\n" " richcmpfunc tp_richcompare;\n" "\n" " /* weak reference enabler */\n" " Py_ssize_t tp_weaklistoffset;\n" "\n" " /* Iterators */\n" " getiterfunc tp_iter;\n" " iternextfunc tp_iternext;\n" "\n" " /* Attribute descriptor and subclassing stuff */\n" " struct PyMethodDef *tp_methods;\n" " struct PyMemberDef *tp_members;\n" " struct PyGetSetDef *tp_getset;\n" " // Strong reference on a heap type, borrowed reference on a static type\n" " struct _typeobject *tp_base;\n" " PyObject *tp_dict;\n" " descrgetfunc tp_descr_get;\n" " descrsetfunc tp_descr_set;\n" " Py_ssize_t tp_dictoffset;\n" " initproc tp_init;\n" " allocfunc tp_alloc;\n" " newfunc tp_new;\n" " freefunc tp_free; /* Low-level free-memory routine */\n" " inquiry tp_is_gc; /* For PyObject_IS_GC */\n" " PyObject *tp_bases;\n" " PyObject *tp_mro; /* method resolution order */\n" " PyObject *tp_cache;\n" " PyObject *tp_subclasses;\n" " PyObject *tp_weaklist;\n" " destructor tp_del;\n" "\n" " /* Type attribute cache version tag. Added in version 2.6 */\n" " unsigned int tp_version_tag;\n" "\n" " destructor tp_finalize;\n" " vectorcallfunc tp_vectorcall;\n" "\n" " /* bitset of which type-watchers care about this type */\n" " unsigned char tp_watched;\n" "} PyTypeObject;\n" msgstr "" #: ../Doc/extending/newtypes.rst:20 msgid "" "Now that's a *lot* of methods. Don't worry too much though -- if you have a " "type you want to define, the chances are very good that you will only " "implement a handful of these." msgstr "" "Esos son *muchos* métodos. Sin embargo, no se preocupe demasiado: si tiene " "un tipo que desea definir, es muy probable que solo implemente un puñado de " "estos." #: ../Doc/extending/newtypes.rst:24 msgid "" "As you probably expect by now, we're going to go over this and give more " "information about the various handlers. We won't go in the order they are " "defined in the structure, because there is a lot of historical baggage that " "impacts the ordering of the fields. It's often easiest to find an example " "that includes the fields you need and then change the values to suit your " "new type. ::" msgstr "" "Como probablemente espera ahora, vamos a repasar esto y daremos más " "información sobre los diversos controladores. No iremos en el orden en que " "se definen en la estructura, porque hay mucho equipaje histórico que afecta " "el orden de los campos. A menudo es más fácil encontrar un ejemplo que " "incluya los campos que necesita y luego cambiar los valores para adaptarlos " "a su nuevo tipo. ::" #: ../Doc/extending/newtypes.rst:31 msgid "const char *tp_name; /* For printing */" msgstr "" #: ../Doc/extending/newtypes.rst:33 msgid "" "The name of the type -- as mentioned in the previous chapter, this will " "appear in various places, almost entirely for diagnostic purposes. Try to " "choose something that will be helpful in such a situation! ::" msgstr "" "El nombre del tipo -- como se mencionó en el capítulo anterior, aparecerá en " "varios lugares, casi por completo para fines de diagnóstico. ¡Intente elegir " "algo que sea útil en tal situación! ::" #: ../Doc/extending/newtypes.rst:37 msgid "Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */" msgstr "" #: ../Doc/extending/newtypes.rst:39 msgid "" "These fields tell the runtime how much memory to allocate when new objects " "of this type are created. Python has some built-in support for variable " "length structures (think: strings, tuples) which is where the :c:member:" "`~PyTypeObject.tp_itemsize` field comes in. This will be dealt with " "later. ::" msgstr "" "Estos campos le dicen al tiempo de ejecución cuánta memoria asignar cuando " "se crean nuevos objetos de este tipo. Python tiene algún soporte incorporado " "para estructuras de longitud variable (piense: cadenas, tuplas) que es donde " "entra el campo :c:member:`~PyTypeObject.tp_itemsize`. Esto se tratará más " "adelante. ::" #: ../Doc/extending/newtypes.rst:44 msgid "const char *tp_doc;" msgstr "" #: ../Doc/extending/newtypes.rst:46 msgid "" "Here you can put a string (or its address) that you want returned when the " "Python script references ``obj.__doc__`` to retrieve the doc string." msgstr "" "Aquí puede poner una cadena de caracteres (o su dirección) que desea que se " "retorne cuando el script de Python haga referencia a ``obj.__doc__`` para " "recuperar el docstring." #: ../Doc/extending/newtypes.rst:49 msgid "" "Now we come to the basic type methods -- the ones most extension types will " "implement." msgstr "" "Ahora llegamos a los métodos de tipo básicos: los que implementarán la " "mayoría de los tipos de extensión." #: ../Doc/extending/newtypes.rst:54 msgid "Finalization and De-allocation" msgstr "Finalización y desasignación" #: ../Doc/extending/newtypes.rst:64 msgid "destructor tp_dealloc;" msgstr "" #: ../Doc/extending/newtypes.rst:66 msgid "" "This function is called when the reference count of the instance of your " "type is reduced to zero and the Python interpreter wants to reclaim it. If " "your type has memory to free or other clean-up to perform, you can put it " "here. The object itself needs to be freed here as well. Here is an example " "of this function::" msgstr "" "Se llama a esta función cuando el recuento de referencia de la instancia de " "su tipo se reduce a cero y el intérprete de Python quiere reclamarlo. Si su " "tipo tiene memoria para liberar u otra limpieza para realizar, puede ponerla " "aquí. El objeto en sí mismo necesita ser liberado aquí también. Aquí hay un " "ejemplo de esta función::" #: ../Doc/extending/newtypes.rst:72 msgid "" "static void\n" "newdatatype_dealloc(newdatatypeobject *obj)\n" "{\n" " free(obj->obj_UnderlyingDatatypePtr);\n" " Py_TYPE(obj)->tp_free((PyObject *)obj);\n" "}" msgstr "" #: ../Doc/extending/newtypes.rst:79 msgid "" "If your type supports garbage collection, the destructor should call :c:func:" "`PyObject_GC_UnTrack` before clearing any member fields::" msgstr "" "Si su tipo admite la recolección de basura, el destructor debe llamar a :c:" "func:`PyObject_GC_UnTrack` antes de borrar cualquier campo miembro:" #: ../Doc/extending/newtypes.rst:82 msgid "" "static void\n" "newdatatype_dealloc(newdatatypeobject *obj)\n" "{\n" " PyObject_GC_UnTrack(obj);\n" " Py_CLEAR(obj->other_obj);\n" " ...\n" " Py_TYPE(obj)->tp_free((PyObject *)obj);\n" "}" msgstr "" #: ../Doc/extending/newtypes.rst:95 msgid "" "One important requirement of the deallocator function is that it leaves any " "pending exceptions alone. This is important since deallocators are " "frequently called as the interpreter unwinds the Python stack; when the " "stack is unwound due to an exception (rather than normal returns), nothing " "is done to protect the deallocators from seeing that an exception has " "already been set. Any actions which a deallocator performs which may cause " "additional Python code to be executed may detect that an exception has been " "set. This can lead to misleading errors from the interpreter. The proper " "way to protect against this is to save a pending exception before performing " "the unsafe action, and restoring it when done. This can be done using the :" "c:func:`PyErr_Fetch` and :c:func:`PyErr_Restore` functions::" msgstr "" "Un requisito importante de la función desasignador es que deja solo las " "excepciones pendientes. Esto es importante ya que los desasignadores se " "llaman con frecuencia cuando el intérprete desenrolla la pila de Python; " "cuando la pila se desenrolla debido a una excepción (en lugar de retornos " "normales), no se hace nada para proteger a los desasignadores de memoria " "(*deallocator*) de ver que ya se ha establecido una excepción. Cualquier " "acción que realice un desasignador que pueda hacer que se ejecute código " "Python adicional puede detectar que se ha establecido una excepción. Esto " "puede conducir a errores engañosos del intérprete. La forma correcta de " "protegerse contra esto es guardar una excepción pendiente antes de realizar " "la acción insegura y restaurarla cuando haya terminado. Esto se puede hacer " "usando las funciones :c:func:`PyErr_Fetch` y :c:func:`PyErr_Restore`::" #: ../Doc/extending/newtypes.rst:107 msgid "" "static void\n" "my_dealloc(PyObject *obj)\n" "{\n" " MyObject *self = (MyObject *) obj;\n" " PyObject *cbresult;\n" "\n" " if (self->my_callback != NULL) {\n" " PyObject *err_type, *err_value, *err_traceback;\n" "\n" " /* This saves the current exception state */\n" " PyErr_Fetch(&err_type, &err_value, &err_traceback);\n" "\n" " cbresult = PyObject_CallNoArgs(self->my_callback);\n" " if (cbresult == NULL)\n" " PyErr_WriteUnraisable(self->my_callback);\n" " else\n" " Py_DECREF(cbresult);\n" "\n" " /* This restores the saved exception state */\n" " PyErr_Restore(err_type, err_value, err_traceback);\n" "\n" " Py_DECREF(self->my_callback);\n" " }\n" " Py_TYPE(obj)->tp_free((PyObject*)self);\n" "}" msgstr "" #: ../Doc/extending/newtypes.rst:134 msgid "" "There are limitations to what you can safely do in a deallocator function. " "First, if your type supports garbage collection (using :c:member:" "`~PyTypeObject.tp_traverse` and/or :c:member:`~PyTypeObject.tp_clear`), some " "of the object's members can have been cleared or finalized by the time :c:" "member:`~PyTypeObject.tp_dealloc` is called. Second, in :c:member:" "`~PyTypeObject.tp_dealloc`, your object is in an unstable state: its " "reference count is equal to zero. Any call to a non-trivial object or API " "(as in the example above) might end up calling :c:member:`~PyTypeObject." "tp_dealloc` again, causing a double free and a crash." msgstr "" "Existen limitaciones para lo que puede hacer de manera segura en una función " "de desasignación. Primero, si su tipo admite la recolección de basura " "(usando :c:member:`~PyTypeObject.tp_traverse` o :c:member:`~PyTypeObject." "tp_clear`), algunos de los miembros del objeto pueden haber sido borrados o " "finalizados por el time :c:member:`~PyTypeObject.tp_dealloc` es llamado. " "Segundo, en :c:member:`~PyTypeObject.tp_dealloc`, su objeto está en un " "estado inestable: su recuento de referencia es igual a cero. Cualquier " "llamada a un objeto o API no trivial (como en el ejemplo anterior) podría " "terminar llamando :c:member:`~PyTypeObject.tp_dealloc` nuevamente, causando " "una doble liberación y un bloqueo." #: ../Doc/extending/newtypes.rst:143 msgid "" "Starting with Python 3.4, it is recommended not to put any complex " "finalization code in :c:member:`~PyTypeObject.tp_dealloc`, and instead use " "the new :c:member:`~PyTypeObject.tp_finalize` type method." msgstr "" "Comenzando con Python 3.4, se recomienda no poner ningún código de " "finalización complejo en :c:member:`~PyTypeObject.tp_dealloc`, y en su lugar " "use el nuevo método de tipo :c:member:`~PyTypeObject.tp_finalize`." #: ../Doc/extending/newtypes.rst:148 msgid ":pep:`442` explains the new finalization scheme." msgstr ":pep:`442` explica el nuevo esquema de finalización." #: ../Doc/extending/newtypes.rst:155 msgid "Object Presentation" msgstr "Presentación de objetos" #: ../Doc/extending/newtypes.rst:157 msgid "" "In Python, there are two ways to generate a textual representation of an " "object: the :func:`repr` function, and the :func:`str` function. (The :func:" "`print` function just calls :func:`str`.) These handlers are both optional." msgstr "" "En Python, hay dos formas de generar una representación textual de un " "objeto: la función :func:`repr`, y la función :func:`str`. (La función :func:" "`print` solo llama a :func:`str`.) Estos controladores son opcionales." #: ../Doc/extending/newtypes.rst:163 msgid "" "reprfunc tp_repr;\n" "reprfunc tp_str;" msgstr "" #: ../Doc/extending/newtypes.rst:166 msgid "" "The :c:member:`~PyTypeObject.tp_repr` handler should return a string object " "containing a representation of the instance for which it is called. Here is " "a simple example::" msgstr "" "El manejador :c:member:`~PyTypeObject.tp_repr` debe retornar un objeto de " "cadena que contenga una representación de la instancia para la que se llama. " "Aquí hay un ejemplo simple::" #: ../Doc/extending/newtypes.rst:170 #, python-format msgid "" "static PyObject *\n" "newdatatype_repr(newdatatypeobject *obj)\n" "{\n" " return PyUnicode_FromFormat(\"Repr-ified_newdatatype{{size:%d}}\",\n" " obj->obj_UnderlyingDatatypePtr->size);\n" "}" msgstr "" #: ../Doc/extending/newtypes.rst:177 msgid "" "If no :c:member:`~PyTypeObject.tp_repr` handler is specified, the " "interpreter will supply a representation that uses the type's :c:member:" "`~PyTypeObject.tp_name` and a uniquely identifying value for the object." msgstr "" "Si no se especifica un controlador :c:member:`~PyTypeObject.tp_repr`, el " "intérprete proporcionará una representación que utiliza el :c:member:" "`~PyTypeObject.tp_name` del tipo y un valor de identificación exclusivo para " "el objeto." #: ../Doc/extending/newtypes.rst:181 msgid "" "The :c:member:`~PyTypeObject.tp_str` handler is to :func:`str` what the :c:" "member:`~PyTypeObject.tp_repr` handler described above is to :func:`repr`; " "that is, it is called when Python code calls :func:`str` on an instance of " "your object. Its implementation is very similar to the :c:member:" "`~PyTypeObject.tp_repr` function, but the resulting string is intended for " "human consumption. If :c:member:`~PyTypeObject.tp_str` is not specified, " "the :c:member:`~PyTypeObject.tp_repr` handler is used instead." msgstr "" "El manejador :c:member:`~PyTypeObject.tp_str` es para :func:`str` lo que el " "manejador :c:member:`~PyTypeObject.tp_repr` descrito arriba es para :func:" "`repr`; es decir, se llama cuando el código Python llama :func:`str` en una " "instancia de su objeto. Su implementación es muy similar a la función :c:" "member:`~PyTypeObject.tp_repr`, pero la cadena resultante está destinada al " "consumo humano. Si :c:member:`~PyTypeObject.tp_str` no se especifica, en su " "lugar se utiliza el controlador :c:member:`~PyTypeObject.tp_repr`." #: ../Doc/extending/newtypes.rst:188 msgid "Here is a simple example::" msgstr "Aquí hay un ejemplo simple::" #: ../Doc/extending/newtypes.rst:190 #, python-format msgid "" "static PyObject *\n" "newdatatype_str(newdatatypeobject *obj)\n" "{\n" " return PyUnicode_FromFormat(\"Stringified_newdatatype{{size:%d}}\",\n" " obj->obj_UnderlyingDatatypePtr->size);\n" "}" msgstr "" #: ../Doc/extending/newtypes.rst:200 msgid "Attribute Management" msgstr "Gestión de atributos" #: ../Doc/extending/newtypes.rst:202 msgid "" "For every object which can support attributes, the corresponding type must " "provide the functions that control how the attributes are resolved. There " "needs to be a function which can retrieve attributes (if any are defined), " "and another to set attributes (if setting attributes is allowed). Removing " "an attribute is a special case, for which the new value passed to the " "handler is ``NULL``." msgstr "" "Para cada objeto que puede soportar atributos, el tipo correspondiente debe " "proporcionar las funciones que controlan cómo se resuelven los atributos. Es " "necesario que haya una función que pueda recuperar atributos (si hay alguna " "definida), y otra para establecer atributos (si se permite establecer " "atributos). La eliminación de un atributo es un caso especial, para el cual " "el nuevo valor pasado al controlador es ``NULL``." #: ../Doc/extending/newtypes.rst:208 msgid "" "Python supports two pairs of attribute handlers; a type that supports " "attributes only needs to implement the functions for one pair. The " "difference is that one pair takes the name of the attribute as a :c:expr:" "`char\\*`, while the other accepts a :c:expr:`PyObject*`. Each type can use " "whichever pair makes more sense for the implementation's convenience. ::" msgstr "" "Python admite dos pares de controladores de atributos; un tipo que admite " "atributos solo necesita implementar las funciones para un par. La diferencia " "es que un par toma el nombre del atributo como :c:expr:`char\\*`, mientras " "que el otro acepta un :c:expr:`PyObject*`. Cada tipo puede usar cualquier " "par que tenga más sentido para la conveniencia de la implementación. ::" #: ../Doc/extending/newtypes.rst:214 msgid "" "getattrfunc tp_getattr; /* char * version */\n" "setattrfunc tp_setattr;\n" "/* ... */\n" "getattrofunc tp_getattro; /* PyObject * version */\n" "setattrofunc tp_setattro;" msgstr "" #: ../Doc/extending/newtypes.rst:220 msgid "" "If accessing attributes of an object is always a simple operation (this will " "be explained shortly), there are generic implementations which can be used " "to provide the :c:expr:`PyObject*` version of the attribute management " "functions. The actual need for type-specific attribute handlers almost " "completely disappeared starting with Python 2.2, though there are many " "examples which have not been updated to use some of the new generic " "mechanism that is available." msgstr "" "Si acceder a los atributos de un objeto siempre es una operación simple " "(esto se explicará en breve), existen implementaciones genéricas que se " "pueden usar para proporcionar la versión :c:expr:`PyObject*` de las " "funciones de administración de atributos. La necesidad real de controladores " "de atributos específicos de tipo desapareció casi por completo a partir de " "Python 2.2, aunque hay muchos ejemplos que no se han actualizado para usar " "algunos de los nuevos mecanismos genéricos disponibles." #: ../Doc/extending/newtypes.rst:231 msgid "Generic Attribute Management" msgstr "Gestión de atributos genéricos" #: ../Doc/extending/newtypes.rst:233 msgid "" "Most extension types only use *simple* attributes. So, what makes the " "attributes simple? There are only a couple of conditions that must be met:" msgstr "" "La mayoría de los tipos de extensión solo usan atributos *simple*. Entonces, " "¿qué hace que los atributos sean simples? Solo hay un par de condiciones que " "se deben cumplir:" #: ../Doc/extending/newtypes.rst:236 msgid "" "The name of the attributes must be known when :c:func:`PyType_Ready` is " "called." msgstr "" "El nombre de los atributos debe ser conocido cuando :c:func:`PyType_Ready` " "es llamado." #: ../Doc/extending/newtypes.rst:239 msgid "" "No special processing is needed to record that an attribute was looked up or " "set, nor do actions need to be taken based on the value." msgstr "" "No se necesita un procesamiento especial para registrar que un atributo se " "buscó o se configuró, ni se deben tomar acciones basadas en el valor." #: ../Doc/extending/newtypes.rst:242 msgid "" "Note that this list does not place any restrictions on the values of the " "attributes, when the values are computed, or how relevant data is stored." msgstr "" "Tenga en cuenta que esta lista no impone restricciones a los valores de los " "atributos, cuándo se calculan los valores o cómo se almacenan los datos " "relevantes." #: ../Doc/extending/newtypes.rst:245 msgid "" "When :c:func:`PyType_Ready` is called, it uses three tables referenced by " "the type object to create :term:`descriptor`\\s which are placed in the " "dictionary of the type object. Each descriptor controls access to one " "attribute of the instance object. Each of the tables is optional; if all " "three are ``NULL``, instances of the type will only have attributes that are " "inherited from their base type, and should leave the :c:member:" "`~PyTypeObject.tp_getattro` and :c:member:`~PyTypeObject.tp_setattro` fields " "``NULL`` as well, allowing the base type to handle attributes." msgstr "" "Cuando se llama a :c:func:`PyType_Ready`, utiliza tres tablas a las que hace " "referencia el objeto de tipo para crear :term:`descriptor` que se colocan en " "el diccionario del objeto de tipo. Cada descriptor controla el acceso a un " "atributo del objeto de instancia. Cada una de las tablas es opcional; si los " "tres son ``NULL``, las instancias del tipo solo tendrán atributos que se " "heredan de su tipo base, y deberían dejar :c:member:`~PyTypeObject." "tp_getattro` y los campos :c:member:`~PyTypeObject.tp_setattro` ``NULL`` " "también, permitiendo que el tipo base maneje los atributos." #: ../Doc/extending/newtypes.rst:253 msgid "The tables are declared as three fields of the type object::" msgstr "Las tablas se declaran como tres campos del tipo objeto::" #: ../Doc/extending/newtypes.rst:255 msgid "" "struct PyMethodDef *tp_methods;\n" "struct PyMemberDef *tp_members;\n" "struct PyGetSetDef *tp_getset;" msgstr "" #: ../Doc/extending/newtypes.rst:259 msgid "" "If :c:member:`~PyTypeObject.tp_methods` is not ``NULL``, it must refer to an " "array of :c:type:`PyMethodDef` structures. Each entry in the table is an " "instance of this structure::" msgstr "" "Si :c:member:`~PyTypeObject.tp_methods` no es ``NULL``, debe referirse a un " "arreglo de estructuras :c:type:`PyMethodDef`. Cada entrada en la tabla es " "una instancia de esta estructura::" #: ../Doc/extending/newtypes.rst:263 msgid "" "typedef struct PyMethodDef {\n" " const char *ml_name; /* method name */\n" " PyCFunction ml_meth; /* implementation function */\n" " int ml_flags; /* flags */\n" " const char *ml_doc; /* docstring */\n" "} PyMethodDef;" msgstr "" #: ../Doc/extending/newtypes.rst:270 #, fuzzy msgid "" "One entry should be defined for each method provided by the type; no entries " "are needed for methods inherited from a base type. One additional entry is " "needed at the end; it is a sentinel that marks the end of the array. The :c:" "member:`~PyMethodDef.ml_name` field of the sentinel must be ``NULL``." msgstr "" "Se debe definir una entrada para cada método proporcionado por el tipo; No " "se necesitan entradas para los métodos heredados de un tipo base. Se " "necesita una entrada adicional al final; es un centinela el que marca el " "final del arreglo. El campo :attr:`ml_name` del centinela debe ser ``NULL``." #: ../Doc/extending/newtypes.rst:275 msgid "" "The second table is used to define attributes which map directly to data " "stored in the instance. A variety of primitive C types are supported, and " "access may be read-only or read-write. The structures in the table are " "defined as::" msgstr "" "La segunda tabla se utiliza para definir atributos que se asignan " "directamente a los datos almacenados en la instancia. Se admite una variedad " "de tipos C primitivos, y el acceso puede ser de solo lectura o lectura-" "escritura. Las estructuras en la tabla se definen como::" #: ../Doc/extending/newtypes.rst:279 msgid "" "typedef struct PyMemberDef {\n" " const char *name;\n" " int type;\n" " int offset;\n" " int flags;\n" " const char *doc;\n" "} PyMemberDef;" msgstr "" #: ../Doc/extending/newtypes.rst:287 #, fuzzy msgid "" "For each entry in the table, a :term:`descriptor` will be constructed and " "added to the type which will be able to extract a value from the instance " "structure. The :c:member:`~PyMemberDef.type` field should contain a type " "code like :c:macro:`Py_T_INT` or :c:macro:`Py_T_DOUBLE`; the value will be " "used to determine how to convert Python values to and from C values. The :c:" "member:`~PyMemberDef.flags` field is used to store flags which control how " "the attribute can be accessed: you can set it to :c:macro:`Py_READONLY` to " "prevent Python code from setting it." msgstr "" "Para cada entrada en la tabla, se construirá un :term:`descriptor` y se " "agregará al tipo que podrá extraer un valor de la estructura de la " "instancia. El campo :attr:`type` debe contener uno de los códigos de tipo " "definidos en el encabezado :file:`structmember.h`; el valor se usará para " "determinar cómo convertir los valores de Python hacia y desde los valores de " "C. El campo :attr:`flags` se usa para almacenar flags que controlan cómo se " "puede acceder al atributo." #: ../Doc/extending/newtypes.rst:295 #, fuzzy msgid "" "An interesting advantage of using the :c:member:`~PyTypeObject.tp_members` " "table to build descriptors that are used at runtime is that any attribute " "defined this way can have an associated doc string simply by providing the " "text in the table. An application can use the introspection API to retrieve " "the descriptor from the class object, and get the doc string using its :attr:" "`~type.__doc__` attribute." msgstr "" "Una ventaja interesante de usar la tabla :c:member:`~PyTypeObject." "tp_members` para crear descriptores que se usan en tiempo de ejecución es " "que cualquier atributo definido de esta manera puede tener un docstring " "asociada simplemente al proporcionar el texto en la tabla. Una aplicación " "puede usar la API de introspección para recuperar el descriptor del objeto " "de clase y obtener el docstring utilizando su atributo :attr:`__doc__`." #: ../Doc/extending/newtypes.rst:301 #, fuzzy msgid "" "As with the :c:member:`~PyTypeObject.tp_methods` table, a sentinel entry " "with a :c:member:`~PyMethodDef.ml_name` value of ``NULL`` is required." msgstr "" "Al igual que con la tabla :c:member:`~PyTypeObject.tp_methods`, se requiere " "una entrada de centinela con un valor :attr:`name` de ``NULL``." #: ../Doc/extending/newtypes.rst:315 msgid "Type-specific Attribute Management" msgstr "Gestión de atributos específicos de tipo" #: ../Doc/extending/newtypes.rst:317 msgid "" "For simplicity, only the :c:expr:`char\\*` version will be demonstrated " "here; the type of the name parameter is the only difference between the :c:" "expr:`char\\*` and :c:expr:`PyObject*` flavors of the interface. This " "example effectively does the same thing as the generic example above, but " "does not use the generic support added in Python 2.2. It explains how the " "handler functions are called, so that if you do need to extend their " "functionality, you'll understand what needs to be done." msgstr "" "Para simplificar, solo la versión :c:expr:`char\\*` será demostrada aquí; el " "tipo del parámetro con nombre es la única diferencia entre :c:expr:`char\\*` " "y :c:expr:`PyObject*` de la interfaz. Este ejemplo efectivamente hace lo " "mismo que el ejemplo genérico anterior, pero no usa el soporte genérico " "agregado en Python 2.2. Explica cómo se llaman las funciones del " "controlador, de modo que si necesita ampliar su funcionalidad, comprenderá " "lo que debe hacerse." #: ../Doc/extending/newtypes.rst:325 #, fuzzy msgid "" "The :c:member:`~PyTypeObject.tp_getattr` handler is called when the object " "requires an attribute look-up. It is called in the same situations where " "the :meth:`~object.__getattr__` method of a class would be called." msgstr "" "Se llama al manejador :c:member:`~PyTypeObject.tp_getattr` cuando el objeto " "requiere una búsqueda de atributo. Se llama en las mismas situaciones donde " "se llamaría el método :meth:`__getattr__` de una clase." #: ../Doc/extending/newtypes.rst:329 msgid "Here is an example::" msgstr "Aquí hay un ejemplo::" #: ../Doc/extending/newtypes.rst:331 #, python-format msgid "" "static PyObject *\n" "newdatatype_getattr(newdatatypeobject *obj, char *name)\n" "{\n" " if (strcmp(name, \"data\") == 0)\n" " {\n" " return PyLong_FromLong(obj->data);\n" " }\n" "\n" " PyErr_Format(PyExc_AttributeError,\n" " \"'%.100s' object has no attribute '%.400s'\",\n" " Py_TYPE(obj)->tp_name, name);\n" " return NULL;\n" "}" msgstr "" #: ../Doc/extending/newtypes.rst:345 #, fuzzy msgid "" "The :c:member:`~PyTypeObject.tp_setattr` handler is called when the :meth:" "`~object.__setattr__` or :meth:`~object.__delattr__` method of a class " "instance would be called. When an attribute should be deleted, the third " "parameter will be ``NULL``. Here is an example that simply raises an " "exception; if this were really all you wanted, the :c:member:`~PyTypeObject." "tp_setattr` handler should be set to ``NULL``. ::" msgstr "" "Se llama al manejador :c:member:`~PyTypeObject.tp_setattr` cuando se llama " "al método :meth:`__setattr__` o :meth:`__delattr__` de una instancia de " "clase. Cuando se debe eliminar un atributo, el tercer parámetro será " "``NULL``. Aquí hay un ejemplo que simplemente plantea una excepción; si esto " "fuera realmente todo lo que deseaba, el controlador :c:member:`~PyTypeObject." "tp_setattr` debería establecerse en ``NULL``. ::" #: ../Doc/extending/newtypes.rst:351 #, python-format msgid "" "static int\n" "newdatatype_setattr(newdatatypeobject *obj, char *name, PyObject *v)\n" "{\n" " PyErr_Format(PyExc_RuntimeError, \"Read-only attribute: %s\", name);\n" " return -1;\n" "}" msgstr "" #: ../Doc/extending/newtypes.rst:359 msgid "Object Comparison" msgstr "Comparación de Objetos" #: ../Doc/extending/newtypes.rst:363 msgid "richcmpfunc tp_richcompare;" msgstr "" #: ../Doc/extending/newtypes.rst:365 #, fuzzy msgid "" "The :c:member:`~PyTypeObject.tp_richcompare` handler is called when " "comparisons are needed. It is analogous to the :ref:`rich comparison " "methods `, like :meth:`!__lt__`, and also called by :c:func:" "`PyObject_RichCompare` and :c:func:`PyObject_RichCompareBool`." msgstr "" "Se llama al manejador :c:member:`~PyTypeObject.tp_richcompare` cuando se " "necesitan comparaciones. Es análogo a :ref:`métodos de comparación ricos " "`, como :meth:`__lt__`, y también llamado por :c:func:" "`PyObject_RichCompare` y :c:func:`PyObject_RichCompareBool`." #: ../Doc/extending/newtypes.rst:370 msgid "" "This function is called with two Python objects and the operator as " "arguments, where the operator is one of ``Py_EQ``, ``Py_NE``, ``Py_LE``, " "``Py_GE``, ``Py_LT`` or ``Py_GT``. It should compare the two objects with " "respect to the specified operator and return ``Py_True`` or ``Py_False`` if " "the comparison is successful, ``Py_NotImplemented`` to indicate that " "comparison is not implemented and the other object's comparison method " "should be tried, or ``NULL`` if an exception was set." msgstr "" "Esta función se llama con dos objetos de Python y el operador como " "argumentos, donde el operador es uno de ``Py_EQ``, ``Py_NE``, ``Py_LE``, " "``Py_GE``, ``Py_LT`` o ``Py_GT``. Debe comparar los dos objetos con respecto " "al operador especificado y retornar ``Py_True`` o ``Py_False`` si la " "comparación es exitosa, ``Py_NotImplemented`` para indicar que la " "comparación no está implementada y se debe probar el método de comparación " "del otro objeto, o ``NULL`` si se estableció una excepción." #: ../Doc/extending/newtypes.rst:378 msgid "" "Here is a sample implementation, for a datatype that is considered equal if " "the size of an internal pointer is equal::" msgstr "" "Aquí hay una implementación de muestra, para un tipo de datos que se " "considera igual si el tamaño de un puntero interno es igual:" #: ../Doc/extending/newtypes.rst:381 msgid "" "static PyObject *\n" "newdatatype_richcmp(newdatatypeobject *obj1, newdatatypeobject *obj2, int " "op)\n" "{\n" " PyObject *result;\n" " int c, size1, size2;\n" "\n" " /* code to make sure that both arguments are of type\n" " newdatatype omitted */\n" "\n" " size1 = obj1->obj_UnderlyingDatatypePtr->size;\n" " size2 = obj2->obj_UnderlyingDatatypePtr->size;\n" "\n" " switch (op) {\n" " case Py_LT: c = size1 < size2; break;\n" " case Py_LE: c = size1 <= size2; break;\n" " case Py_EQ: c = size1 == size2; break;\n" " case Py_NE: c = size1 != size2; break;\n" " case Py_GT: c = size1 > size2; break;\n" " case Py_GE: c = size1 >= size2; break;\n" " }\n" " result = c ? Py_True : Py_False;\n" " Py_INCREF(result);\n" " return result;\n" " }" msgstr "" #: ../Doc/extending/newtypes.rst:408 msgid "Abstract Protocol Support" msgstr "Soporte de protocolo abstracto" #: ../Doc/extending/newtypes.rst:410 msgid "" "Python supports a variety of *abstract* 'protocols;' the specific interfaces " "provided to use these interfaces are documented in :ref:`abstract`." msgstr "" "Python admite una variedad de protocolos *abstractos*; las interfaces " "específicas proporcionadas para usar estas interfaces están documentadas en :" "ref:`abstract`." #: ../Doc/extending/newtypes.rst:414 msgid "" "A number of these abstract interfaces were defined early in the development " "of the Python implementation. In particular, the number, mapping, and " "sequence protocols have been part of Python since the beginning. Other " "protocols have been added over time. For protocols which depend on several " "handler routines from the type implementation, the older protocols have been " "defined as optional blocks of handlers referenced by the type object. For " "newer protocols there are additional slots in the main type object, with a " "flag bit being set to indicate that the slots are present and should be " "checked by the interpreter. (The flag bit does not indicate that the slot " "values are non-``NULL``. The flag may be set to indicate the presence of a " "slot, but a slot may still be unfilled.) ::" msgstr "" "Varias de estas interfaces abstractas se definieron temprano en el " "desarrollo de la implementación de Python. En particular, los protocolos de " "número, mapeo y secuencia han sido parte de Python desde el principio. Se " "han agregado otros protocolos con el tiempo. Para los protocolos que " "dependen de varias rutinas de controlador de la implementación de tipo, los " "protocolos más antiguos se han definido como bloques opcionales de " "controladores a los que hace referencia el objeto de tipo. Para los " "protocolos más nuevos, hay espacios adicionales en el objeto de tipo " "principal, con un bit de marca que se establece para indicar que los " "espacios están presentes y el intérprete debe verificarlos. (El bit de " "indicador no indica que los valores de intervalo no son ``NULL``. El " "indicador puede establecerse para indicar la presencia de un intervalo, pero " "un intervalo aún puede estar vacío.)::" #: ../Doc/extending/newtypes.rst:425 msgid "" "PyNumberMethods *tp_as_number;\n" "PySequenceMethods *tp_as_sequence;\n" "PyMappingMethods *tp_as_mapping;" msgstr "" #: ../Doc/extending/newtypes.rst:429 msgid "" "If you wish your object to be able to act like a number, a sequence, or a " "mapping object, then you place the address of a structure that implements " "the C type :c:type:`PyNumberMethods`, :c:type:`PySequenceMethods`, or :c:" "type:`PyMappingMethods`, respectively. It is up to you to fill in this " "structure with appropriate values. You can find examples of the use of each " "of these in the :file:`Objects` directory of the Python source " "distribution. ::" msgstr "" "Si desea que su objeto pueda actuar como un número, una secuencia o un " "objeto de mapeo, entonces coloca la dirección de una estructura que " "implementa el tipo C :c:type:`PyNumberMethods`, :c:type:`PySequenceMethods`, " "o :c:type:`PyMappingMethods`, respectivamente. Depende de usted completar " "esta estructura con los valores apropiados. Puede encontrar ejemplos del uso " "de cada uno de estos en el directorio :file:`Objects` de la distribución " "fuente de Python. ::" #: ../Doc/extending/newtypes.rst:436 msgid "hashfunc tp_hash;" msgstr "" #: ../Doc/extending/newtypes.rst:438 msgid "" "This function, if you choose to provide it, should return a hash number for " "an instance of your data type. Here is a simple example::" msgstr "" "Esta función, si elige proporcionarla, debería retornar un número hash para " "una instancia de su tipo de datos. Aquí hay un ejemplo simple::" #: ../Doc/extending/newtypes.rst:441 msgid "" "static Py_hash_t\n" "newdatatype_hash(newdatatypeobject *obj)\n" "{\n" " Py_hash_t result;\n" " result = obj->some_size + 32767 * obj->some_number;\n" " if (result == -1)\n" " result = -2;\n" " return result;\n" "}" msgstr "" #: ../Doc/extending/newtypes.rst:451 msgid "" ":c:type:`Py_hash_t` is a signed integer type with a platform-varying width. " "Returning ``-1`` from :c:member:`~PyTypeObject.tp_hash` indicates an error, " "which is why you should be careful to avoid returning it when hash " "computation is successful, as seen above." msgstr "" ":c:type:`Py_hash_t` es un tipo entero con signo con un ancho que varia " "dependiendo de la plataforma.retornar ``-1`` de :c:member:`~PyTypeObject." "tp_hash` indica un error, por lo que debe tener cuidado de evitar retornarlo " "cuando el cálculo de hash sea exitoso, como se vio anteriormente." #: ../Doc/extending/newtypes.rst:458 msgid "ternaryfunc tp_call;" msgstr "" #: ../Doc/extending/newtypes.rst:460 msgid "" "This function is called when an instance of your data type is \"called\", " "for example, if ``obj1`` is an instance of your data type and the Python " "script contains ``obj1('hello')``, the :c:member:`~PyTypeObject.tp_call` " "handler is invoked." msgstr "" "Esta función se llama cuando una instancia de su tipo de datos se \"llama\", " "por ejemplo, si ``obj1`` es una instancia de su tipo de datos y el script de " "Python contiene ``obj1('hello')``, el controlador :c:member:`~PyTypeObject." "tp_call` se invoca." #: ../Doc/extending/newtypes.rst:464 msgid "This function takes three arguments:" msgstr "Esta función toma tres argumentos:" #: ../Doc/extending/newtypes.rst:466 msgid "" "*self* is the instance of the data type which is the subject of the call. If " "the call is ``obj1('hello')``, then *self* is ``obj1``." msgstr "" "*self* es la instancia del tipo de datos que es el sujeto de la llamada. Si " "la llamada es ``obj1('hola')``, entonces *self* es ``obj1``." #: ../Doc/extending/newtypes.rst:469 msgid "" "*args* is a tuple containing the arguments to the call. You can use :c:func:" "`PyArg_ParseTuple` to extract the arguments." msgstr "" "*args* es una tupla que contiene los argumentos de la llamada. Puede usar :c:" "func:`PyArg_ParseTuple` para extraer los argumentos." #: ../Doc/extending/newtypes.rst:472 msgid "" "*kwds* is a dictionary of keyword arguments that were passed. If this is non-" "``NULL`` and you support keyword arguments, use :c:func:" "`PyArg_ParseTupleAndKeywords` to extract the arguments. If you do not want " "to support keyword arguments and this is non-``NULL``, raise a :exc:" "`TypeError` with a message saying that keyword arguments are not supported." msgstr "" "*kwds* es un diccionario de argumentos de palabras clave que se pasaron. Si " "no es ``NULL`` y admite argumentos de palabras clave, use :c:func:" "`PyArg_ParseTupleAndKeywords` para extraer los argumentos. Si no desea " "admitir argumentos de palabras clave y esto no es ``NULL``, genere un :exc:" "`TypeError` con un mensaje que indique que los argumentos de palabras clave " "no son compatibles." #: ../Doc/extending/newtypes.rst:478 msgid "Here is a toy ``tp_call`` implementation::" msgstr "Aquí hay una implementación de juguete ``tp_call``::" #: ../Doc/extending/newtypes.rst:480 #, python-format msgid "" "static PyObject *\n" "newdatatype_call(newdatatypeobject *obj, PyObject *args, PyObject *kwds)\n" "{\n" " PyObject *result;\n" " const char *arg1;\n" " const char *arg2;\n" " const char *arg3;\n" "\n" " if (!PyArg_ParseTuple(args, \"sss:call\", &arg1, &arg2, &arg3)) {\n" " return NULL;\n" " }\n" " result = PyUnicode_FromFormat(\n" " \"Returning -- value: [%d] arg1: [%s] arg2: [%s] arg3: [%s]\\n\",\n" " obj->obj_UnderlyingDatatypePtr->size,\n" " arg1, arg2, arg3);\n" " return result;\n" "}" msgstr "" #: ../Doc/extending/newtypes.rst:500 msgid "" "/* Iterators */\n" "getiterfunc tp_iter;\n" "iternextfunc tp_iternext;" msgstr "" #: ../Doc/extending/newtypes.rst:504 #, fuzzy msgid "" "These functions provide support for the iterator protocol. Both handlers " "take exactly one parameter, the instance for which they are being called, " "and return a new reference. In the case of an error, they should set an " "exception and return ``NULL``. :c:member:`~PyTypeObject.tp_iter` " "corresponds to the Python :meth:`~object.__iter__` method, while :c:member:" "`~PyTypeObject.tp_iternext` corresponds to the Python :meth:`~iterator." "__next__` method." msgstr "" "Estas funciones proporcionan soporte para el protocolo iterador. Ambos " "manejadores toman exactamente un parámetro, la instancia para la que están " "siendo llamados, y retornan una nueva referencia. En el caso de un error, " "deben establecer una excepción y retornar ``NULL``. :c:member:`~PyTypeObject." "tp_iter` corresponde al método Python :meth:`__iter__`, mientras que :c:" "member:`~PyTypeObject.tp_iternext` corresponde al método Python :meth:" "`~iterator.__next__`." #: ../Doc/extending/newtypes.rst:511 msgid "" "Any :term:`iterable` object must implement the :c:member:`~PyTypeObject." "tp_iter` handler, which must return an :term:`iterator` object. Here the " "same guidelines apply as for Python classes:" msgstr "" "Cualquier objeto :term:`iterable` debe implementar el manejador :c:member:" "`~PyTypeObject.tp_iter`, que debe retornar un objeto :term:`iterator`. Aquí " "se aplican las mismas pautas que para las clases de Python:" #: ../Doc/extending/newtypes.rst:515 msgid "" "For collections (such as lists and tuples) which can support multiple " "independent iterators, a new iterator should be created and returned by each " "call to :c:member:`~PyTypeObject.tp_iter`." msgstr "" "Para colecciones (como listas y tuplas) que pueden admitir múltiples " "iteradores independientes, cada llamada debe crear y retornar un nuevo " "iterador a :c:member:`~PyTypeObject.tp_iter`." #: ../Doc/extending/newtypes.rst:518 msgid "" "Objects which can only be iterated over once (usually due to side effects of " "iteration, such as file objects) can implement :c:member:`~PyTypeObject." "tp_iter` by returning a new reference to themselves -- and should also " "therefore implement the :c:member:`~PyTypeObject.tp_iternext` handler." msgstr "" "Los objetos que solo se pueden iterar una vez (generalmente debido a los " "efectos secundarios de la iteración, como los objetos de archivo) pueden " "implementar :c:member:`~PyTypeObject.tp_iter` retornando una nueva " "referencia a ellos mismos y, por lo tanto, también deben implementar el " "manejador :c:member:`~PyTypeObject.tp_iternext`." #: ../Doc/extending/newtypes.rst:523 msgid "" "Any :term:`iterator` object should implement both :c:member:`~PyTypeObject." "tp_iter` and :c:member:`~PyTypeObject.tp_iternext`. An iterator's :c:member:" "`~PyTypeObject.tp_iter` handler should return a new reference to the " "iterator. Its :c:member:`~PyTypeObject.tp_iternext` handler should return a " "new reference to the next object in the iteration, if there is one. If the " "iteration has reached the end, :c:member:`~PyTypeObject.tp_iternext` may " "return ``NULL`` without setting an exception, or it may set :exc:" "`StopIteration` *in addition* to returning ``NULL``; avoiding the exception " "can yield slightly better performance. If an actual error occurs, :c:member:" "`~PyTypeObject.tp_iternext` should always set an exception and return " "``NULL``." msgstr "" "Cualquier objeto :term:`iterator` debe implementar tanto :c:member:" "`~PyTypeObject.tp_iter` como :c:member:`~PyTypeObject.tp_iternext`. El " "manejador de un iterador :c:member:`~PyTypeObject.tp_iter` debería retornar " "una nueva referencia al iterador. Su controlador :c:member:`~PyTypeObject." "tp_iternext` debería retornar una nueva referencia al siguiente objeto en la " "iteración, si hay uno. Si la iteración ha llegado al final, :c:member:" "`~PyTypeObject.tp_iternext` puede retornar ``NULL`` sin establecer una " "excepción, o puede establecer :exc:`StopIteration` *además* para retornar " "``NULL``; evitar la excepción puede producir un rendimiento ligeramente " "mejor. Si se produce un error real, :c:member:`~PyTypeObject.tp_iternext` " "siempre debe establecer una excepción y retornar ``NULL``." #: ../Doc/extending/newtypes.rst:539 msgid "Weak Reference Support" msgstr "Soporte de referencia débil" #: ../Doc/extending/newtypes.rst:541 msgid "" "One of the goals of Python's weak reference implementation is to allow any " "type to participate in the weak reference mechanism without incurring the " "overhead on performance-critical objects (such as numbers)." msgstr "" "Uno de los objetivos de la implementación de referencia débil de Python es " "permitir que cualquier tipo participe en el mecanismo de referencia débil " "sin incurrir en la sobrecarga de objetos críticos para el rendimiento (como " "los números)." #: ../Doc/extending/newtypes.rst:546 msgid "Documentation for the :mod:`weakref` module." msgstr "Documentación para el módulo :mod:`weakref`." #: ../Doc/extending/newtypes.rst:548 msgid "" "For an object to be weakly referenceable, the extension type must set the " "``Py_TPFLAGS_MANAGED_WEAKREF`` bit of the :c:member:`~PyTypeObject.tp_flags` " "field. The legacy :c:member:`~PyTypeObject.tp_weaklistoffset` field should " "be left as zero." msgstr "" #: ../Doc/extending/newtypes.rst:553 #, fuzzy msgid "" "Concretely, here is how the statically declared type object would look::" msgstr "" "Y el miembro correspondiente en el objeto de tipo declarado estáticamente:" #: ../Doc/extending/newtypes.rst:555 msgid "" "static PyTypeObject TrivialType = {\n" " PyVarObject_HEAD_INIT(NULL, 0)\n" " /* ... other members omitted for brevity ... */\n" " .tp_flags = Py_TPFLAGS_MANAGED_WEAKREF | ...,\n" "};" msgstr "" #: ../Doc/extending/newtypes.rst:562 #, fuzzy msgid "" "The only further addition is that ``tp_dealloc`` needs to clear any weak " "references (by calling :c:func:`PyObject_ClearWeakRefs`)::" msgstr "" "La única adición adicional es que ``tp_dealloc`` necesita borrar cualquier " "referencia débil (llamando a :c:func:`PyObject_ClearWeakRefs`) si el campo " "no es ``NULL`` ::" #: ../Doc/extending/newtypes.rst:565 msgid "" "static void\n" "Trivial_dealloc(TrivialObject *self)\n" "{\n" " /* Clear weakrefs first before calling any destructors */\n" " PyObject_ClearWeakRefs((PyObject *) self);\n" " /* ... remainder of destruction code omitted for brevity ... */\n" " Py_TYPE(self)->tp_free((PyObject *) self);\n" "}" msgstr "" #: ../Doc/extending/newtypes.rst:576 msgid "More Suggestions" msgstr "Más Sugerencias" #: ../Doc/extending/newtypes.rst:578 msgid "" "In order to learn how to implement any specific method for your new data " "type, get the :term:`CPython` source code. Go to the :file:`Objects` " "directory, then search the C source files for ``tp_`` plus the function you " "want (for example, ``tp_richcompare``). You will find examples of the " "function you want to implement." msgstr "" "Para aprender a implementar cualquier método específico para su nuevo tipo " "de datos, obtenga el código fuente :term:`CPython`. Vaya al directorio :file:" "`Objects`, luego busque en los archivos fuente C ``tp_`` más la función que " "desee (por ejemplo, ``tp_richcompare``). Encontrará ejemplos de la función " "que desea implementar." #: ../Doc/extending/newtypes.rst:584 msgid "" "When you need to verify that an object is a concrete instance of the type " "you are implementing, use the :c:func:`PyObject_TypeCheck` function. A " "sample of its use might be something like the following::" msgstr "" "Cuando necesite verificar que un objeto es una instancia concreta del tipo " "que está implementando, use la función :c:func:`PyObject_TypeCheck`. Una " "muestra de su uso podría ser algo como lo siguiente::" #: ../Doc/extending/newtypes.rst:588 msgid "" "if (!PyObject_TypeCheck(some_object, &MyType)) {\n" " PyErr_SetString(PyExc_TypeError, \"arg #1 not a mything\");\n" " return NULL;\n" "}" msgstr "" #: ../Doc/extending/newtypes.rst:595 msgid "Download CPython source releases." msgstr "Descargue las versiones de origen de CPython." #: ../Doc/extending/newtypes.rst:595 msgid "https://www.python.org/downloads/source/" msgstr "https://www.python.org/downloads/source/" #: ../Doc/extending/newtypes.rst:597 msgid "" "The CPython project on GitHub, where the CPython source code is developed." msgstr "" "El proyecto CPython en GitHub, donde se desarrolla el código fuente de " "CPython." #: ../Doc/extending/newtypes.rst:598 msgid "https://github.com/python/cpython" msgstr "https://github.com/python/cpython" #: ../Doc/extending/newtypes.rst:56 msgid "object" msgstr "" #: ../Doc/extending/newtypes.rst:56 msgid "deallocation" msgstr "" #: ../Doc/extending/newtypes.rst:56 msgid "deallocation, object" msgstr "" #: ../Doc/extending/newtypes.rst:56 msgid "finalization" msgstr "" #: ../Doc/extending/newtypes.rst:56 #, fuzzy msgid "finalization, of objects" msgstr "Finalización y desasignación" #: ../Doc/extending/newtypes.rst:91 msgid "PyErr_Fetch (C function)" msgstr "" #: ../Doc/extending/newtypes.rst:91 msgid "PyErr_Restore (C function)" msgstr "" #: ../Doc/extending/newtypes.rst:150 msgid "string" msgstr "" #: ../Doc/extending/newtypes.rst:150 #, fuzzy msgid "object representation" msgstr "Presentación de objetos" #: ../Doc/extending/newtypes.rst:150 msgid "built-in function" msgstr "" #: ../Doc/extending/newtypes.rst:150 msgid "repr" msgstr ""