# 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: 2023-10-12 19:43+0200\n" "PO-Revision-Date: 2021-12-09 23:44-0300\n" "Last-Translator: Cristián Maureira-Fredes \n" "Language-Team: python-doc-es\n" "Language: es\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" "Generated-By: Babel 2.13.0\n" #: ../Doc/reference/datamodel.rst:6 msgid "Data model" msgstr "Modelo de datos" #: ../Doc/reference/datamodel.rst:12 msgid "Objects, values and types" msgstr "Objetos, valores y tipos" #: ../Doc/reference/datamodel.rst:18 msgid "" ":dfn:`Objects` are Python's abstraction for data. All data in a Python " "program is represented by objects or by relations between objects. (In a " "sense, and in conformance to Von Neumann's model of a \"stored program " "computer\", code is also represented by objects.)" msgstr "" ":dfn:`Objects` son la abstracción de Python para los datos. Todos los datos " "en un programa Python están representados por objetos o por relaciones entre " "objetos. (En cierto sentido y de conformidad con el modelo de Von Neumann de " "una \"programa almacenado de computadora\", el código también está " "representado por objetos.)" #: ../Doc/reference/datamodel.rst:35 msgid "" "Every object has an identity, a type and a value. An object's *identity* " "never changes once it has been created; you may think of it as the object's " "address in memory. The ':keyword:`is`' operator compares the identity of " "two objects; the :func:`id` function returns an integer representing its " "identity." msgstr "" "Cada objeto tiene una identidad, un tipo y un valor. La *identidad* de un " "objeto nunca cambia una vez que ha sido creado; puede pensar en ello como la " "dirección del objeto en la memoria. El operador ':keyword:`is`' compara la " "identidad de dos objetos; la función :func:`id` retorna un número entero que " "representa su identidad." #: ../Doc/reference/datamodel.rst:42 msgid "For CPython, ``id(x)`` is the memory address where ``x`` is stored." msgstr "" "Para CPython, ``id(x)`` es la dirección de memoria donde se almacena ``x``." #: ../Doc/reference/datamodel.rst:44 msgid "" "An object's type determines the operations that the object supports (e.g., " "\"does it have a length?\") and also defines the possible values for objects " "of that type. The :func:`type` function returns an object's type (which is " "an object itself). Like its identity, an object's :dfn:`type` is also " "unchangeable. [#]_" msgstr "" "El tipo de un objeto determina las operaciones que admite el objeto (por " "ejemplo, \"¿tiene una longitud?\") y también define los posibles valores " "para los objetos de ese tipo. La función :func:`type` retorna el tipo de un " "objeto (que es un objeto en sí mismo). Al igual que su identidad, también " "el :dfn:`type` de un objeto es inmutable. [#]_" #: ../Doc/reference/datamodel.rst:50 msgid "" "The *value* of some objects can change. Objects whose value can change are " "said to be *mutable*; objects whose value is unchangeable once they are " "created are called *immutable*. (The value of an immutable container object " "that contains a reference to a mutable object can change when the latter's " "value is changed; however the container is still considered immutable, " "because the collection of objects it contains cannot be changed. So, " "immutability is not strictly the same as having an unchangeable value, it is " "more subtle.) An object's mutability is determined by its type; for " "instance, numbers, strings and tuples are immutable, while dictionaries and " "lists are mutable." msgstr "" "El *valor* de algunos objetos puede cambiar. Se dice que los objetos cuyo " "valor puede cambiar son *mutables*; Los objetos cuyo valor no se puede " "modificar una vez que se crean se denominan *inmutables*. (El valor de un " "objeto contenedor inmutable que contiene una referencia a un objeto mutable " "puede cambiar cuando se cambia el valor de este último; sin embargo, el " "contenedor todavía se considera inmutable, porque la colección de objetos " "que contiene no se puede cambiar. Por lo tanto, la inmutabilidad no es " "estrictamente lo mismo que tener un valor inmutable, es más sutil). La " "mutabilidad de un objeto está determinada por su tipo; por ejemplo, los " "números, las cadenas de caracteres y las tuplas son inmutables, mientras que " "los diccionarios y las listas son mutables." #: ../Doc/reference/datamodel.rst:65 msgid "" "Objects are never explicitly destroyed; however, when they become " "unreachable they may be garbage-collected. An implementation is allowed to " "postpone garbage collection or omit it altogether --- it is a matter of " "implementation quality how garbage collection is implemented, as long as no " "objects are collected that are still reachable." msgstr "" "Los objetos nunca se destruyen explícitamente; sin embargo, cuando se " "vuelven inalcanzables, se pueden recolectar basura. Se permite a una " "implementación posponer la recolección de basura u omitirla por completo; es " "una cuestión de calidad de la implementación cómo se implementa la " "recolección de basura, siempre que no se recolecten objetos que todavía sean " "accesibles." #: ../Doc/reference/datamodel.rst:73 msgid "" "CPython currently uses a reference-counting scheme with (optional) delayed " "detection of cyclically linked garbage, which collects most objects as soon " "as they become unreachable, but is not guaranteed to collect garbage " "containing circular references. See the documentation of the :mod:`gc` " "module for information on controlling the collection of cyclic garbage. " "Other implementations act differently and CPython may change. Do not depend " "on immediate finalization of objects when they become unreachable (so you " "should always close files explicitly)." msgstr "" "CPython actualmente utiliza un esquema de conteo de referencias con " "detección retardada (opcional) de basura enlazada cíclicamente, que " "recolecta la mayoría de los objetos tan pronto como se vuelven " "inalcanzables, pero no se garantiza que recolecte basura que contenga " "referencias circulares. Vea la documentación del módulo :mod:`gc` para " "información sobre el control de la recolección de basura cíclica. Otras " "implementaciones actúan de manera diferente y CPython puede cambiar. No " "dependa de la finalización inmediata de los objetos cuando se vuelvan " "inalcanzables (por lo que siempre debe cerrar los archivos explícitamente)." #: ../Doc/reference/datamodel.rst:82 msgid "" "Note that the use of the implementation's tracing or debugging facilities " "may keep objects alive that would normally be collectable. Also note that " "catching an exception with a ':keyword:`try`...\\ :keyword:`except`' " "statement may keep objects alive." msgstr "" "Tenga en cuenta que el uso de las funciones de rastreo o depuración de la " "implementación puede mantener activos los objetos que normalmente serían " "coleccionables. También tenga en cuenta que la captura de una excepción con " "una sentencia ':keyword:`try`...\\ :keyword:`except`' puede mantener objetos " "activos." #: ../Doc/reference/datamodel.rst:87 msgid "" "Some objects contain references to \"external\" resources such as open files " "or windows. It is understood that these resources are freed when the object " "is garbage-collected, but since garbage collection is not guaranteed to " "happen, such objects also provide an explicit way to release the external " "resource, usually a :meth:`close` method. Programs are strongly recommended " "to explicitly close such objects. The ':keyword:`try`...\\ :keyword:" "`finally`' statement and the ':keyword:`with`' statement provide convenient " "ways to do this." msgstr "" "Algunos objetos contienen referencias a recursos \"externos\" como archivos " "abiertos o ventanas. Se entiende que estos recursos se liberan cuando el " "objeto es eliminado por el recolector de basura, pero como no se garantiza " "que la recolección de basura suceda, dichos objetos también proporcionan una " "forma explícita de liberar el recurso externo, generalmente un método :meth:" "`close`. Se recomienda encarecidamente a los programas cerrar explícitamente " "dichos objetos. La declaración ':keyword:`try`...\\ :keyword:`finally`' y la " "declaración ':keyword:`with`' proporcionan formas convenientes de hacer esto." #: ../Doc/reference/datamodel.rst:97 msgid "" "Some objects contain references to other objects; these are called " "*containers*. Examples of containers are tuples, lists and dictionaries. " "The references are part of a container's value. In most cases, when we talk " "about the value of a container, we imply the values, not the identities of " "the contained objects; however, when we talk about the mutability of a " "container, only the identities of the immediately contained objects are " "implied. So, if an immutable container (like a tuple) contains a reference " "to a mutable object, its value changes if that mutable object is changed." msgstr "" "Algunos objetos contienen referencias a otros objetos; estos se llaman " "*contenedores*. Ejemplos de contenedores son tuplas, listas y diccionarios. " "Las referencias son parte del valor de un contenedor. En la mayoría de los " "casos, cuando hablamos del valor de un contenedor, implicamos los valores, " "no las identidades de los objetos contenidos; sin embargo, cuando hablamos " "de la mutabilidad de un contenedor, solo se implican las identidades de los " "objetos contenidos inmediatamente. Entonces, si un contenedor inmutable " "(como una tupla) contiene una referencia a un objeto mutable, su valor " "cambia si se cambia ese objeto mutable." #: ../Doc/reference/datamodel.rst:106 msgid "" "Types affect almost all aspects of object behavior. Even the importance of " "object identity is affected in some sense: for immutable types, operations " "that compute new values may actually return a reference to any existing " "object with the same type and value, while for mutable objects this is not " "allowed. E.g., after ``a = 1; b = 1``, ``a`` and ``b`` may or may not refer " "to the same object with the value one, depending on the implementation, but " "after ``c = []; d = []``, ``c`` and ``d`` are guaranteed to refer to two " "different, unique, newly created empty lists. (Note that ``c = d = []`` " "assigns the same object to both ``c`` and ``d``.)" msgstr "" "Los tipos afectan a casi todos los aspectos del comportamiento del objeto. " "Incluso la importancia de la identidad del objeto se ve afectada en cierto " "sentido: para los tipos inmutables, las operaciones que calculan nuevos " "valores en realidad pueden retornar una referencia a cualquier objeto " "existente con el mismo tipo y valor, mientras que para los objetos mutables " "esto no está permitido. Por ejemplo, al hacer ``a = 1; b = 1``, ``a`` y " "``b`` puede o no referirse al mismo objeto con el valor 1, dependiendo de la " "implementación, pero al hacer ``c = []; d = []``, ``c`` y ``d`` se garantiza " "que se refieren a dos listas vacías diferentes, únicas y recién creadas. " "(Tenga en cuenta que ``c = d = []`` asigna el mismo objeto a ambos ``c`` y " "``d``.)" #: ../Doc/reference/datamodel.rst:120 msgid "The standard type hierarchy" msgstr "Jerarquía de tipos estándar" #: ../Doc/reference/datamodel.rst:129 msgid "" "Below is a list of the types that are built into Python. Extension modules " "(written in C, Java, or other languages, depending on the implementation) " "can define additional types. Future versions of Python may add types to the " "type hierarchy (e.g., rational numbers, efficiently stored arrays of " "integers, etc.), although such additions will often be provided via the " "standard library instead." msgstr "" "A continuación se muestra una lista de los tipos integrados en Python. Los " "módulos de extensión (escritos en C, Java u otros lenguajes, dependiendo de " "la implementación) pueden definir tipos adicionales. Las versiones futuras " "de Python pueden agregar tipos a la jerarquía de tipos (por ejemplo, números " "racionales, matrices de enteros almacenados de manera eficiente, etc.), " "aunque tales adiciones a menudo se proporcionarán a través de la biblioteca " "estándar." #: ../Doc/reference/datamodel.rst:140 msgid "" "Some of the type descriptions below contain a paragraph listing 'special " "attributes.' These are attributes that provide access to the implementation " "and are not intended for general use. Their definition may change in the " "future." msgstr "" "Algunas de las descripciones de tipos a continuación contienen un párrafo " "que enumera 'atributos especiales'. Estos son atributos que proporcionan " "acceso a la implementación y no están destinados para uso general. Su " "definición puede cambiar en el futuro." #: ../Doc/reference/datamodel.rst:146 ../Doc/reference/datamodel.rst:148 msgid "None" msgstr "None" #: ../Doc/reference/datamodel.rst:150 msgid "" "This type has a single value. There is a single object with this value. " "This object is accessed through the built-in name ``None``. It is used to " "signify the absence of a value in many situations, e.g., it is returned from " "functions that don't explicitly return anything. Its truth value is false." msgstr "" "Este tipo tiene un solo valor. Hay un solo objeto con este valor. Se accede " "a este objeto a través del nombre incorporado ``None``. Se utiliza para " "indicar la ausencia de un valor en muchas situaciones, por ejemplo, se " "retorna desde funciones que no retornan nada explícitamente. Su valor de " "verdad es falso." #: ../Doc/reference/datamodel.rst:157 ../Doc/reference/datamodel.rst:159 msgid "NotImplemented" msgstr "NotImplemented" #: ../Doc/reference/datamodel.rst:161 msgid "" "This type has a single value. There is a single object with this value. " "This object is accessed through the built-in name ``NotImplemented``. " "Numeric methods and rich comparison methods should return this value if they " "do not implement the operation for the operands provided. (The interpreter " "will then try the reflected operation, or some other fallback, depending on " "the operator.) It should not be evaluated in a boolean context." msgstr "" "Este tipo tiene un solo valor. Hay un solo objeto con este valor. Se accede " "a este objeto a través del nombre integrado ``NotImplemented``. Los métodos " "numéricos y los métodos de comparación enriquecidos deben retornar este " "valor si no implementan la operación para los operandos proporcionados. (El " "intérprete intentará entonces la operación reflejada, o alguna otra " "alternativa, dependiendo del operador). No debe evaluarse en un contexto " "booleano." #: ../Doc/reference/datamodel.rst:168 msgid "See :ref:`implementing-the-arithmetic-operations` for more details." msgstr "Vea :ref:`implementing-the-arithmetic-operations` para más detalles." #: ../Doc/reference/datamodel.rst:172 msgid "" "Evaluating ``NotImplemented`` in a boolean context is deprecated. While it " "currently evaluates as true, it will emit a :exc:`DeprecationWarning`. It " "will raise a :exc:`TypeError` in a future version of Python." msgstr "" "La evaluación de ``NotImplemented`` en un contexto booleano está en desuso. " "Si bien actualmente se evalúa como verdadero, lanzará un :exc:" "`DeprecationWarning`. Lanzará un :exc:`TypeError` en una versión futura de " "Python." #: ../Doc/reference/datamodel.rst:179 ../Doc/reference/datamodel.rst:180 msgid "Ellipsis" msgstr "Elipsis" #: ../Doc/reference/datamodel.rst:184 msgid "" "This type has a single value. There is a single object with this value. " "This object is accessed through the literal ``...`` or the built-in name " "``Ellipsis``. Its truth value is true." msgstr "" "Este tipo tiene un solo valor. Hay un solo objeto con este valor. Se accede " "a este objeto a través del literal ``...`` o el nombre incorporado " "``Ellipsis``. Su valor de verdad es verdadero." #: ../Doc/reference/datamodel.rst:190 msgid ":class:`numbers.Number`" msgstr ":class:`numbers.Number`" #: ../Doc/reference/datamodel.rst:194 msgid "" "These are created by numeric literals and returned as results by arithmetic " "operators and arithmetic built-in functions. Numeric objects are immutable; " "once created their value never changes. Python numbers are of course " "strongly related to mathematical numbers, but subject to the limitations of " "numerical representation in computers." msgstr "" "Estos son creados por literales numéricos y retornados como resultados por " "operadores aritméticos y funciones aritméticas integradas. Los objetos " "numéricos son inmutables; una vez creado su valor nunca cambia. Los números " "de Python están, por supuesto, fuertemente relacionados con los números " "matemáticos, pero están sujetos a las limitaciones de la representación " "numérica en las computadoras." #: ../Doc/reference/datamodel.rst:200 msgid "" "The string representations of the numeric classes, computed by :meth:" "`~object.__repr__` and :meth:`~object.__str__`, have the following " "properties:" msgstr "" "Las representaciones de cadena de caracteres de las clases numéricas, " "calculadas por :meth:`~object.__repr__` y :meth:`~object.__str__`, tienen " "las siguientes propiedades:" #: ../Doc/reference/datamodel.rst:204 msgid "" "They are valid numeric literals which, when passed to their class " "constructor, produce an object having the value of the original numeric." msgstr "" "Son literales numéricos válidos que, cuando se pasan a su constructor de " "clase, producen un objeto que tiene el valor del numérico original." #: ../Doc/reference/datamodel.rst:208 msgid "The representation is in base 10, when possible." msgstr "La representación está en base 10, cuando sea posible." #: ../Doc/reference/datamodel.rst:210 msgid "" "Leading zeros, possibly excepting a single zero before a decimal point, are " "not shown." msgstr "" "Los ceros iniciales, posiblemente excepto un solo cero antes de un punto " "decimal, no se muestran." #: ../Doc/reference/datamodel.rst:213 msgid "" "Trailing zeros, possibly excepting a single zero after a decimal point, are " "not shown." msgstr "" "Los ceros finales, posiblemente excepto un solo cero después de un punto " "decimal, no se muestran." #: ../Doc/reference/datamodel.rst:216 msgid "A sign is shown only when the number is negative." msgstr "Solo se muestra un signo cuando el número es negativo." #: ../Doc/reference/datamodel.rst:218 msgid "" "Python distinguishes between integers, floating point numbers, and complex " "numbers:" msgstr "" "Python distingue entre números enteros, números de coma flotante y números " "complejos:" #: ../Doc/reference/datamodel.rst:223 msgid ":class:`numbers.Integral`" msgstr ":class:`numbers.Integral`" #: ../Doc/reference/datamodel.rst:227 msgid "" "These represent elements from the mathematical set of integers (positive and " "negative)." msgstr "" "Estos representan elementos del conjunto matemático de números enteros " "(positivo y negativo)." #: ../Doc/reference/datamodel.rst:233 msgid "" "The rules for integer representation are intended to give the most " "meaningful interpretation of shift and mask operations involving negative " "integers." msgstr "" "Las reglas para la representación de enteros están destinadas a dar la " "interpretación más significativa de las operaciones de cambio y máscara que " "involucran enteros negativos." #: ../Doc/reference/datamodel.rst:236 msgid "There are two types of integers:" msgstr "Hay dos tipos de números enteros:" #: ../Doc/reference/datamodel.rst:243 msgid "Integers (:class:`int`)" msgstr "Enteros (:class:`int`)" #: ../Doc/reference/datamodel.rst:239 msgid "" "These represent numbers in an unlimited range, subject to available " "(virtual) memory only. For the purpose of shift and mask operations, a " "binary representation is assumed, and negative numbers are represented in a " "variant of 2's complement which gives the illusion of an infinite string of " "sign bits extending to the left." msgstr "" "Estos representan números en un rango ilimitado, sujetos solo a la memoria " "(virtual) disponible. Para las operaciones de desplazamiento y máscara, se " "asume una representación binaria, y los números negativos se representan en " "una variante del complemento de 2 que da la ilusión de una cadena de " "caracteres infinita de bits con signo que se extiende hacia la izquierda." #: ../Doc/reference/datamodel.rst:256 msgid "Booleans (:class:`bool`)" msgstr "Booleanos (:class:`bool`)" #: ../Doc/reference/datamodel.rst:251 msgid "" "These represent the truth values False and True. The two objects " "representing the values ``False`` and ``True`` are the only Boolean objects. " "The Boolean type is a subtype of the integer type, and Boolean values behave " "like the values 0 and 1, respectively, in almost all contexts, the exception " "being that when converted to a string, the strings ``\"False\"`` or " "``\"True\"`` are returned, respectively." msgstr "" "Estos representan los valores de verdad Falso y Verdadero. Los dos objetos " "que representan los valores ``False`` y ``True`` son los únicos objetos " "booleanos. El tipo booleano es un subtipo del tipo entero y los valores " "booleanos se comportan como los valores 0 y 1 respectivamente, en casi todos " "los contextos, con la excepción de que cuando se convierten en una cadena de " "caracteres, las cadenas de caracteres ``\"False\"`` o ``\"True\"`` son " "retornadas respectivamente." #: ../Doc/reference/datamodel.rst:259 msgid ":class:`numbers.Real` (:class:`float`)" msgstr ":class:`numbers.Real` (:class:`float`)" #: ../Doc/reference/datamodel.rst:267 msgid "" "These represent machine-level double precision floating point numbers. You " "are at the mercy of the underlying machine architecture (and C or Java " "implementation) for the accepted range and handling of overflow. Python does " "not support single-precision floating point numbers; the savings in " "processor and memory usage that are usually the reason for using these are " "dwarfed by the overhead of using objects in Python, so there is no reason to " "complicate the language with two kinds of floating point numbers." msgstr "" "Estos representan números de punto flotante de precisión doble a nivel de " "máquina. Está a merced de la arquitectura de la máquina subyacente (y la " "implementación de C o Java) para el rango aceptado y el manejo del " "desbordamiento. Python no admite números de coma flotante de precisión " "simple; el ahorro en el uso del procesador y la memoria, que generalmente " "son la razón para usarlos, se ven reducidos por la sobrecarga del uso de " "objetos en Python, por lo que no hay razón para complicar el lenguaje con " "dos tipos de números de coma flotante." #: ../Doc/reference/datamodel.rst:277 msgid ":class:`numbers.Complex` (:class:`complex`)" msgstr ":class:`numbers.Complex` (:class:`complex`)" #: ../Doc/reference/datamodel.rst:283 msgid "" "These represent complex numbers as a pair of machine-level double precision " "floating point numbers. The same caveats apply as for floating point " "numbers. The real and imaginary parts of a complex number ``z`` can be " "retrieved through the read-only attributes ``z.real`` and ``z.imag``." msgstr "" "Estos representan números complejos como un par de números de coma flotante " "de precisión doble a nivel de máquina. Se aplican las mismas advertencias " "que para los números de coma flotante. Las partes reales e imaginarias de un " "número complejo ``z`` se pueden obtener a través de los atributos de solo " "lectura ``z.real`` y ``z.imag``." #: ../Doc/reference/datamodel.rst:290 msgid "Sequences" msgstr "Secuencias" #: ../Doc/reference/datamodel.rst:299 msgid "" "These represent finite ordered sets indexed by non-negative numbers. The " "built-in function :func:`len` returns the number of items of a sequence. " "When the length of a sequence is *n*, the index set contains the numbers 0, " "1, ..., *n*-1. Item *i* of sequence *a* is selected by ``a[i]``." msgstr "" "Estos representan conjuntos ordenados finitos indexados por números no " "negativos. La función incorporada :func:`len` retorna el número de elementos " "de una secuencia. Cuando la longitud de una secuencia es *n*, el conjunto de " "índices contiene los números 0, 1, ..., *n*-1. El elemento *i* de la " "secuencia *a* se selecciona mediante ``a[i]``." #: ../Doc/reference/datamodel.rst:306 msgid "" "Sequences also support slicing: ``a[i:j]`` selects all items with index *k* " "such that *i* ``<=`` *k* ``<`` *j*. When used as an expression, a slice is " "a sequence of the same type. This implies that the index set is renumbered " "so that it starts at 0." msgstr "" "Las secuencias también admiten segmentación: ``a[i:j]`` selecciona todos los " "elementos con índice *k* de modo que *i* ``<=`` *k* ``<`` *j*. Cuando se " "usa como una expresión, un segmento es una secuencia del mismo tipo. Esto " "implica que el conjunto de índices se vuelve a enumerar para que comience en " "0." #: ../Doc/reference/datamodel.rst:311 msgid "" "Some sequences also support \"extended slicing\" with a third \"step\" " "parameter: ``a[i:j:k]`` selects all items of *a* with index *x* where ``x = " "i + n*k``, *n* ``>=`` ``0`` and *i* ``<=`` *x* ``<`` *j*." msgstr "" "Algunas secuencias también admiten \"segmentación extendida\" con un tercer " "parámetro \"paso\" : ``a[i:j:k]`` selecciona todos los elementos de *a* con " "índice *x* donde ``x = i + n*k``, *n* ``>=`` ``0`` y *i* ``<=`` *x* ``<`` " "*j*." #: ../Doc/reference/datamodel.rst:315 msgid "Sequences are distinguished according to their mutability:" msgstr "Las secuencias se distinguen según su mutabilidad:" #: ../Doc/reference/datamodel.rst:319 msgid "Immutable sequences" msgstr "Secuencias inmutables" #: ../Doc/reference/datamodel.rst:325 msgid "" "An object of an immutable sequence type cannot change once it is created. " "(If the object contains references to other objects, these other objects may " "be mutable and may be changed; however, the collection of objects directly " "referenced by an immutable object cannot change.)" msgstr "" "Un objeto de un tipo de secuencia inmutable no puede cambiar una vez que se " "crea. (Si el objeto contiene referencias a otros objetos, estos otros " "objetos pueden ser mutables y pueden cambiarse; sin embargo, la colección de " "objetos a los que hace referencia directamente un objeto inmutable no puede " "cambiar)." #: ../Doc/reference/datamodel.rst:330 msgid "The following types are immutable sequences:" msgstr "Los siguientes tipos son secuencias inmutables:" #: ../Doc/reference/datamodel.rst:353 msgid "Strings" msgstr "Cadenas de caracteres" #: ../Doc/reference/datamodel.rst:343 msgid "" "A string is a sequence of values that represent Unicode code points. All the " "code points in the range ``U+0000 - U+10FFFF`` can be represented in a " "string. Python doesn't have a :c:expr:`char` type; instead, every code " "point in the string is represented as a string object with length ``1``. " "The built-in function :func:`ord` converts a code point from its string form " "to an integer in the range ``0 - 10FFFF``; :func:`chr` converts an integer " "in the range ``0 - 10FFFF`` to the corresponding length ``1`` string " "object. :meth:`str.encode` can be used to convert a :class:`str` to :class:" "`bytes` using the given text encoding, and :meth:`bytes.decode` can be used " "to achieve the opposite." msgstr "" "Una cadena es una secuencia de valores que representan puntos de código " "Unicode. Todos los puntos de código en el rango ``U+0000 - U+10FFFF`` se " "pueden representar en una cadena. Python no tiene un tipo :c:expr:`char`; en " "su lugar, cada punto de código de la cadena se representa como un objeto de " "cadena con una longitud ``1``. La función integrada :func:`ord` convierte un " "punto de código de su forma de cadena a un entero en el rango ``0 - " "10FFFF``; :func:`chr` convierte un entero en el rango ``0 - 10FFFF`` al " "objeto de cadena ``1`` de longitud correspondiente. :meth:`str.encode` se " "puede usar para convertir un :class:`str` a :class:`bytes` usando la " "codificación de texto dada, y :meth:`bytes.decode` se puede usar para lograr " "lo contrario." #: ../Doc/reference/datamodel.rst:366 msgid "Tuples" msgstr "Tuplas" #: ../Doc/reference/datamodel.rst:361 msgid "" "The items of a tuple are arbitrary Python objects. Tuples of two or more " "items are formed by comma-separated lists of expressions. A tuple of one " "item (a 'singleton') can be formed by affixing a comma to an expression (an " "expression by itself does not create a tuple, since parentheses must be " "usable for grouping of expressions). An empty tuple can be formed by an " "empty pair of parentheses." msgstr "" "Los elementos de una tupla son objetos arbitrarios de Python. Las tuplas de " "dos o más elementos están formadas por listas de expresiones separadas por " "comas. Se puede formar una tupla de un elemento (un 'singleton') al colocar " "una coma en una expresión (una expresión en sí misma no crea una tupla, ya " "que los paréntesis deben ser utilizables para agrupar expresiones). Una " "tupla vacía puede estar formada por un par de paréntesis vacío." #: ../Doc/reference/datamodel.rst:376 msgid "Bytes" msgstr "Bytes" #: ../Doc/reference/datamodel.rst:371 msgid "" "A bytes object is an immutable array. The items are 8-bit bytes, " "represented by integers in the range 0 <= x < 256. Bytes literals (like " "``b'abc'``) and the built-in :func:`bytes()` constructor can be used to " "create bytes objects. Also, bytes objects can be decoded to strings via " "the :meth:`~bytes.decode` method." msgstr "" "Un objeto de bytes es una colección inmutable. Los elementos son bytes de 8 " "bits, representados por enteros en el rango 0 <= x <256. Literales de bytes " "(como ``b'abc'``) y el constructor incorporado :func:`bytes()` se puede " "utilizar para crear objetos de bytes. Además, los objetos de bytes se pueden " "decodificar en cadenas de caracteres a través del método :meth:`~bytes." "decode`." #: ../Doc/reference/datamodel.rst:379 msgid "Mutable sequences" msgstr "Secuencias mutables" #: ../Doc/reference/datamodel.rst:388 msgid "" "Mutable sequences can be changed after they are created. The subscription " "and slicing notations can be used as the target of assignment and :keyword:" "`del` (delete) statements." msgstr "" "Las secuencias mutables se pueden cambiar después de su creación. Las " "anotaciones de suscripción y segmentación se pueden utilizar como el " "objetivo de asignaciones y declaraciones :keyword:`del` (eliminar)." #: ../Doc/reference/datamodel.rst:396 msgid "" "The :mod:`collections` and :mod:`array` module provide additional examples " "of mutable sequence types." msgstr "" "Los módulos :mod:`collections` y :mod:`array` proporcionan ejemplos " "adicionales de tipos de secuencias mutables." #: ../Doc/reference/datamodel.rst:399 msgid "There are currently two intrinsic mutable sequence types:" msgstr "Actualmente hay dos tipos intrínsecos de secuencias mutable:" #: ../Doc/reference/datamodel.rst:406 msgid "Lists" msgstr "Listas" #: ../Doc/reference/datamodel.rst:404 msgid "" "The items of a list are arbitrary Python objects. Lists are formed by " "placing a comma-separated list of expressions in square brackets. (Note that " "there are no special cases needed to form lists of length 0 or 1.)" msgstr "" "Los elementos de una lista son objetos de Python arbitrarios. Las listas se " "forman colocando una lista de expresiones separadas por comas entre " "corchetes. (Tome en cuenta que no hay casos especiales necesarios para " "formar listas de longitud 0 o 1.)" #: ../Doc/reference/datamodel.rst:415 msgid "Byte Arrays" msgstr "Colecciones de bytes" #: ../Doc/reference/datamodel.rst:411 msgid "" "A bytearray object is a mutable array. They are created by the built-in :" "func:`bytearray` constructor. Aside from being mutable (and hence " "unhashable), byte arrays otherwise provide the same interface and " "functionality as immutable :class:`bytes` objects." msgstr "" "Un objeto bytearray es una colección mutable. Son creados por el constructor " "incorporado :func:`bytearray`. Además de ser mutables (y, por lo tanto, " "inquebrantable), las colecciones de bytes proporcionan la misma interfaz y " "funcionalidad que los objetos inmutables :class:`bytes`." #: ../Doc/reference/datamodel.rst:418 msgid "Set types" msgstr "Tipos de conjuntos" #: ../Doc/reference/datamodel.rst:424 msgid "" "These represent unordered, finite sets of unique, immutable objects. As " "such, they cannot be indexed by any subscript. However, they can be iterated " "over, and the built-in function :func:`len` returns the number of items in a " "set. Common uses for sets are fast membership testing, removing duplicates " "from a sequence, and computing mathematical operations such as intersection, " "union, difference, and symmetric difference." msgstr "" "Estos representan conjuntos finitos no ordenados de objetos únicos e " "inmutables. Como tal, no pueden ser indexados por ningún *subscript*. Sin " "embargo, pueden repetirse y la función incorporada :func:`len` retorna el " "número de elementos en un conjunto. Los usos comunes de los conjuntos son " "pruebas rápidas de membresía, eliminación de duplicados de una secuencia y " "cálculo de operaciones matemáticas como intersección, unión, diferencia y " "diferencia simétrica." #: ../Doc/reference/datamodel.rst:431 msgid "" "For set elements, the same immutability rules apply as for dictionary keys. " "Note that numeric types obey the normal rules for numeric comparison: if two " "numbers compare equal (e.g., ``1`` and ``1.0``), only one of them can be " "contained in a set." msgstr "" "Para elementos del conjunto, se aplican las mismas reglas de inmutabilidad " "que para las claves de diccionario. Tenga en cuenta que los tipos numéricos " "obedecen las reglas normales para la comparación numérica: si dos números se " "comparan igual (por ejemplo, ``1`` y ``1.0``), solo uno de ellos puede estar " "contenido en un conjunto." #: ../Doc/reference/datamodel.rst:436 msgid "There are currently two intrinsic set types:" msgstr "Actualmente hay dos tipos de conjuntos intrínsecos:" #: ../Doc/reference/datamodel.rst:445 msgid "Sets" msgstr "Conjuntos" #: ../Doc/reference/datamodel.rst:442 msgid "" "These represent a mutable set. They are created by the built-in :func:`set` " "constructor and can be modified afterwards by several methods, such as :meth:" "`~set.add`." msgstr "" "Estos representan un conjunto mutable. Son creados por el constructor " "incorporado :func:`set` y puede ser modificado posteriormente por varios " "métodos, como :meth:`~set.add`." #: ../Doc/reference/datamodel.rst:454 msgid "Frozen sets" msgstr "Conjuntos congelados" #: ../Doc/reference/datamodel.rst:450 msgid "" "These represent an immutable set. They are created by the built-in :func:" "`frozenset` constructor. As a frozenset is immutable and :term:`hashable`, " "it can be used again as an element of another set, or as a dictionary key." msgstr "" "Estos representan un conjunto inmutable. Son creados por el constructor " "incorporado :func:`frozenset`. Como un conjunto congelado es inmutable y :" "term:`hashable`, se puede usar nuevamente como un elemento de otro conjunto " "o como una clave de un diccionario." #: ../Doc/reference/datamodel.rst:457 msgid "Mappings" msgstr "Mapeos" #: ../Doc/reference/datamodel.rst:464 msgid "" "These represent finite sets of objects indexed by arbitrary index sets. The " "subscript notation ``a[k]`` selects the item indexed by ``k`` from the " "mapping ``a``; this can be used in expressions and as the target of " "assignments or :keyword:`del` statements. The built-in function :func:`len` " "returns the number of items in a mapping." msgstr "" "Estos representan conjuntos finitos de objetos indexados por conjuntos de " "índices arbitrarios. La notación de subíndice ``a[k]`` selecciona el " "elemento indexado por ``k`` del mapeo ``a``; esto se puede usar en " "expresiones y como el objetivo de asignaciones o declaraciones :keyword:" "`del`. La función incorporada :func:`len` retorna el número de elementos en " "un mapeo." #: ../Doc/reference/datamodel.rst:470 msgid "There is currently a single intrinsic mapping type:" msgstr "Actualmente hay un único tipo de mapeo intrínseco:" #: ../Doc/reference/datamodel.rst:474 msgid "Dictionaries" msgstr "Diccionarios" #: ../Doc/reference/datamodel.rst:478 msgid "" "These represent finite sets of objects indexed by nearly arbitrary values. " "The only types of values not acceptable as keys are values containing lists " "or dictionaries or other mutable types that are compared by value rather " "than by object identity, the reason being that the efficient implementation " "of dictionaries requires a key's hash value to remain constant. Numeric " "types used for keys obey the normal rules for numeric comparison: if two " "numbers compare equal (e.g., ``1`` and ``1.0``) then they can be used " "interchangeably to index the same dictionary entry." msgstr "" "Estos representan conjuntos finitos de objetos indexados por valores casi " "arbitrarios. Los únicos tipos de valores no aceptables como claves son " "valores que contienen listas o diccionarios u otros tipos mutables que se " "comparan por valor en lugar de por identidad de objeto, la razón es que la " "implementación eficiente de los diccionarios requiere que el valor *hash* de " "una clave permanezca constante. Los tipos numéricos utilizados para las " "claves obedecen las reglas normales para la comparación numérica: si dos " "números se comparan igual (por ejemplo, ``1`` y ``1.0``) entonces se pueden " "usar indistintamente para indexar la misma entrada del diccionario." #: ../Doc/reference/datamodel.rst:487 msgid "" "Dictionaries preserve insertion order, meaning that keys will be produced in " "the same order they were added sequentially over the dictionary. Replacing " "an existing key does not change the order, however removing a key and re-" "inserting it will add it to the end instead of keeping its old place." msgstr "" "Los diccionarios conservan el orden de inserción, lo que significa que las " "claves se mantendrán en el mismo orden en que se agregaron secuencialmente " "sobre el diccionario. Reemplazar una clave existente no cambia el orden, sin " "embargo, eliminar una clave y volver a insertarla la agregará al final en " "lugar de mantener su lugar anterior." #: ../Doc/reference/datamodel.rst:492 msgid "" "Dictionaries are mutable; they can be created by the ``{...}`` notation (see " "section :ref:`dict`)." msgstr "" "Los diccionarios son mutables; pueden ser creados por la notación ``{...}`` " "(vea la sección :ref:`dict`)." #: ../Doc/reference/datamodel.rst:499 msgid "" "The extension modules :mod:`dbm.ndbm` and :mod:`dbm.gnu` provide additional " "examples of mapping types, as does the :mod:`collections` module." msgstr "" "Los módulos de extensión :mod:`dbm.ndbm` y :mod:`dbm.gnu` proporcionan " "ejemplos adicionales de tipos de mapeo, al igual que el módulo :mod:" "`collections`." #: ../Doc/reference/datamodel.rst:503 msgid "" "Dictionaries did not preserve insertion order in versions of Python before " "3.6. In CPython 3.6, insertion order was preserved, but it was considered an " "implementation detail at that time rather than a language guarantee." msgstr "" "Los diccionarios no conservaban el orden de inserción en las versiones de " "Python anteriores a 3.6. En CPython 3.6, el orden de inserción se conserva, " "pero se consideró un detalle de implementación en ese momento en lugar de " "una garantía de idioma." #: ../Doc/reference/datamodel.rst:510 msgid "Callable types" msgstr "Tipos invocables" #: ../Doc/reference/datamodel.rst:518 msgid "" "These are the types to which the function call operation (see section :ref:" "`calls`) can be applied:" msgstr "" "Estos son los tipos a los que la operación de llamada de función (vea la " "sección :ref:`calls`) puede ser aplicado:" #: ../Doc/reference/datamodel.rst:523 msgid "User-defined functions" msgstr "Funciones definidas por el usuario" #: ../Doc/reference/datamodel.rst:530 msgid "" "A user-defined function object is created by a function definition (see " "section :ref:`function`). It should be called with an argument list " "containing the same number of items as the function's formal parameter list." msgstr "" "Un objeto función definido por el usuario, es creado por un definición de " "función (vea la sección :ref:`function`). Debe llamarse con una lista de " "argumentos que contenga el mismo número de elementos que la lista de " "parámetros formales de la función." #: ../Doc/reference/datamodel.rst:535 ../Doc/reference/datamodel.rst:926 msgid "Special attributes:" msgstr "Atributos especiales:" #: ../Doc/reference/datamodel.rst:554 msgid "Attribute" msgstr "Atributo" #: ../Doc/reference/datamodel.rst:554 msgid "Meaning" msgstr "Significado" #: ../Doc/reference/datamodel.rst:556 ../Doc/reference/datamodel.rst:843 #: ../Doc/reference/datamodel.rst:942 msgid ":attr:`__doc__`" msgstr ":attr:`__doc__`" #: ../Doc/reference/datamodel.rst:556 msgid "" "The function's documentation string, or ``None`` if unavailable; not " "inherited by subclasses." msgstr "" "El texto de documentación de la función, o ``None`` si no está disponible; " "no heredado por subclases." #: ../Doc/reference/datamodel.rst:556 ../Doc/reference/datamodel.rst:561 #: ../Doc/reference/datamodel.rst:564 ../Doc/reference/datamodel.rst:569 #: ../Doc/reference/datamodel.rst:573 ../Doc/reference/datamodel.rst:579 #: ../Doc/reference/datamodel.rst:589 ../Doc/reference/datamodel.rst:600 #: ../Doc/reference/datamodel.rst:610 ../Doc/reference/datamodel.rst:613 msgid "Writable" msgstr "Escribible" #: ../Doc/reference/datamodel.rst:561 msgid ":attr:`~definition.\\ __name__`" msgstr ":attr:`~definition.\\ __name__`" #: ../Doc/reference/datamodel.rst:561 msgid "The function's name." msgstr "El nombre de la función." #: ../Doc/reference/datamodel.rst:564 msgid ":attr:`~definition.\\ __qualname__`" msgstr ":attr:`~definition.\\ __qualname__`" #: ../Doc/reference/datamodel.rst:564 msgid "The function's :term:`qualified name`." msgstr "Las funciones :term:`qualified name`." #: ../Doc/reference/datamodel.rst:569 ../Doc/reference/datamodel.rst:932 msgid ":attr:`__module__`" msgstr ":attr:`__module__`" #: ../Doc/reference/datamodel.rst:569 msgid "" "The name of the module the function was defined in, or ``None`` if " "unavailable." msgstr "" "El nombre del módulo en el que se definió la función, o ``None`` si no está " "disponible." #: ../Doc/reference/datamodel.rst:573 msgid ":attr:`__defaults__`" msgstr ":attr:`__defaults__`" #: ../Doc/reference/datamodel.rst:573 msgid "" "A tuple containing default argument values for those arguments that have " "defaults, or ``None`` if no arguments have a default value." msgstr "" "Una tupla que contiene valores de argumento predeterminados para aquellos " "argumentos que tienen valores predeterminados, o ``None`` si ningún " "argumento tiene un valor predeterminado." #: ../Doc/reference/datamodel.rst:579 msgid ":attr:`__code__`" msgstr ":attr:`__code__`" #: ../Doc/reference/datamodel.rst:579 msgid "The code object representing the compiled function body." msgstr "El objeto de código que representa el cuerpo de la función compilada." #: ../Doc/reference/datamodel.rst:582 msgid ":attr:`__globals__`" msgstr ":attr:`__globals__`" #: ../Doc/reference/datamodel.rst:582 msgid "" "A reference to the dictionary that holds the function's global variables --- " "the global namespace of the module in which the function was defined." msgstr "" "Una referencia al diccionario que contiene las variables globales de la " "función --- el espacio de nombres global del módulo en el que se definió la " "función." #: ../Doc/reference/datamodel.rst:582 ../Doc/reference/datamodel.rst:593 msgid "Read-only" msgstr "Solo lectura" #: ../Doc/reference/datamodel.rst:589 ../Doc/reference/datamodel.rst:935 msgid ":attr:`~object.__dict__`" msgstr ":attr:`~object.__dict__`" #: ../Doc/reference/datamodel.rst:589 msgid "The namespace supporting arbitrary function attributes." msgstr "El espacio de nombres que admite atributos de funciones arbitrarias." #: ../Doc/reference/datamodel.rst:593 msgid ":attr:`__closure__`" msgstr ":attr:`__closure__`" #: ../Doc/reference/datamodel.rst:593 msgid "" "``None`` or a tuple of cells that contain bindings for the function's free " "variables. See below for information on the ``cell_contents`` attribute." msgstr "" "``None`` o una tupla de celdas que contienen enlaces para las variables " "libres de la función. Vea a continuación para obtener información sobre el " "atributo ``cell_contents``." #: ../Doc/reference/datamodel.rst:600 ../Doc/reference/datamodel.rst:858 #: ../Doc/reference/datamodel.rst:949 msgid ":attr:`__annotations__`" msgstr ":attr:`__annotations__`" #: ../Doc/reference/datamodel.rst:600 msgid "" "A dict containing annotations of parameters. The keys of the dict are the " "parameter names, and ``'return'`` for the return annotation, if provided. " "For more information on working with this attribute, see :ref:`annotations-" "howto`." msgstr "" "Un diccionario que contiene anotaciones de parámetros. Las claves del dict " "son los nombres de los parámetros, y ``'return'`` para la anotación de " "retorno, si se proporciona. Para más información sobre trabajar con este " "atributo, ve :ref:`annotations-howto`." #: ../Doc/reference/datamodel.rst:610 msgid ":attr:`__kwdefaults__`" msgstr ":attr:`__kwdefaults__`" #: ../Doc/reference/datamodel.rst:610 msgid "A dict containing defaults for keyword-only parameters." msgstr "" "Un diccionario que contiene valores predeterminados para parámetros de solo " "palabras clave." #: ../Doc/reference/datamodel.rst:613 ../Doc/reference/datamodel.rst:954 msgid ":attr:`__type_params__`" msgstr ":attr:`__type_params__`" #: ../Doc/reference/datamodel.rst:613 msgid "" "A tuple containing the :ref:`type parameters ` of a :ref:" "`generic function `." msgstr "" "Una tupla que contiene el :ref:`type parameters ` de un :ref:" "`generic function `." #: ../Doc/reference/datamodel.rst:620 msgid "" "Most of the attributes labelled \"Writable\" check the type of the assigned " "value." msgstr "" "La mayoría de los atributos etiquetados \"Escribible\" verifican el tipo del " "valor asignado." #: ../Doc/reference/datamodel.rst:622 msgid "" "Function objects also support getting and setting arbitrary attributes, " "which can be used, for example, to attach metadata to functions. Regular " "attribute dot-notation is used to get and set such attributes. *Note that " "the current implementation only supports function attributes on user-defined " "functions. Function attributes on built-in functions may be supported in the " "future.*" msgstr "" "Los objetos de función también admiten la obtención y configuración de " "atributos arbitrarios, que se pueden usar, por ejemplo, para adjuntar " "metadatos a funciones. La notación de puntos de atributo regular se utiliza " "para obtener y establecer dichos atributos. *Tenga en cuenta que la " "implementación actual solo admite atributos de función en funciones " "definidas por el usuario. Los atributos de función en funciones integradas " "pueden ser compatibles en el futuro.*" #: ../Doc/reference/datamodel.rst:628 msgid "" "A cell object has the attribute ``cell_contents``. This can be used to get " "the value of the cell, as well as set the value." msgstr "" "Un objeto de celda tiene el atributo ``cell_contents``. Esto se puede usar " "para obtener el valor de la celda, así como para establecer el valor." #: ../Doc/reference/datamodel.rst:631 msgid "" "Additional information about a function's definition can be retrieved from " "its code object; see the description of internal types below. The :data:" "`cell ` type can be accessed in the :mod:`types` module." msgstr "" "Se puede recuperar información adicional sobre la definición de una función " "desde su objeto de código; Vea la descripción de los tipos internos a " "continuación. El tipo :data:`cell ` puede ser accedido en el " "módulo :mod:`types`." #: ../Doc/reference/datamodel.rst:638 msgid "Instance methods" msgstr "Métodos de instancia" #: ../Doc/reference/datamodel.rst:645 msgid "" "An instance method object combines a class, a class instance and any " "callable object (normally a user-defined function)." msgstr "" "Un objeto de método de instancia combina una clase, una instancia de clase y " "cualquier objeto invocable (normalmente una función definida por el usuario)." #: ../Doc/reference/datamodel.rst:655 msgid "" "Special read-only attributes: :attr:`__self__` is the class instance " "object, :attr:`__func__` is the function object; :attr:`__doc__` is the " "method's documentation (same as ``__func__.__doc__``); :attr:`~definition." "__name__` is the method name (same as ``__func__.__name__``); :attr:" "`__module__` is the name of the module the method was defined in, or " "``None`` if unavailable." msgstr "" "Atributos especiales de solo lectura: :attr:`__self__` es el objeto de " "instancia de clase, :attr:`__func__` es el objeto de función; :attr:" "`__doc__` es la documentación del método (al igual que ``__func__." "__doc__``); :attr:`~definition.__name__` es el nombre del método (al igual " "que ``__func__.__name__``); :attr:`__module__` es el nombre del módulo en el " "que el método fue definido, o ``None`` si no se encuentra disponible." #: ../Doc/reference/datamodel.rst:661 msgid "" "Methods also support accessing (but not setting) the arbitrary function " "attributes on the underlying function object." msgstr "" "Los métodos también admiten obtener (más no establecer) los atributos " "arbitrarios de la función en el objeto de función subyacente." #: ../Doc/reference/datamodel.rst:664 msgid "" "User-defined method objects may be created when getting an attribute of a " "class (perhaps via an instance of that class), if that attribute is a user-" "defined function object or a class method object." msgstr "" "Los objetos de métodos definidos por usuarios pueden ser creados al obtener " "el atributo de una clase (probablemente a través de la instancia de dicha " "clase), si tal atributo es el objeto de una función definida por el usuario " "o el objeto del método de una clase." #: ../Doc/reference/datamodel.rst:668 msgid "" "When an instance method object is created by retrieving a user-defined " "function object from a class via one of its instances, its :attr:`__self__` " "attribute is the instance, and the method object is said to be bound. The " "new method's :attr:`__func__` attribute is the original function object." msgstr "" "Cuando un objeto de instancia de método es creado al obtener un objeto de " "función definida por el usuario desde una clase a través de una de sus " "instancias, su atributo :attr:`__self__` es la instancia, y el objeto de " "método se dice que está enlazado. El nuevo atributo de método :attr:" "`__func__` es el objeto de función original." #: ../Doc/reference/datamodel.rst:674 msgid "" "When an instance method object is created by retrieving a class method " "object from a class or instance, its :attr:`__self__` attribute is the class " "itself, and its :attr:`__func__` attribute is the function object underlying " "the class method." msgstr "" "Cuando un objeto de instancia de método es creado al obtener un objeto de " "método de clase a partir de una clase o instancia, su atributo :attr:" "`__self__` es la clase misma, y su atributo :attr:`__func__` es el objeto de " "función subyacente al método de la clase." #: ../Doc/reference/datamodel.rst:679 msgid "" "When an instance method object is called, the underlying function (:attr:" "`__func__`) is called, inserting the class instance (:attr:`__self__`) in " "front of the argument list. For instance, when :class:`C` is a class which " "contains a definition for a function :meth:`f`, and ``x`` is an instance of :" "class:`C`, calling ``x.f(1)`` is equivalent to calling ``C.f(x, 1)``." msgstr "" "Cuando el objeto de la instancia de método es invocado, la función " "subyacente (:attr:`__func__`) es llamada, insertando la instancia de clase (:" "attr:`__self__`) delante de la lista de argumentos. Por ejemplo, cuando :" "class:`C` es una clase que contiene la definición de una función :meth:`f`, " "y ``x`` es una instancia de :class:`C`, invocar ``x.f(1)`` es equivalente a " "invocar ``C.f(x, 1)``." #: ../Doc/reference/datamodel.rst:686 msgid "" "When an instance method object is derived from a class method object, the " "\"class instance\" stored in :attr:`__self__` will actually be the class " "itself, so that calling either ``x.f(1)`` or ``C.f(1)`` is equivalent to " "calling ``f(C,1)`` where ``f`` is the underlying function." msgstr "" "Cuando el objeto de instancia de método es derivado del objeto del método de " "clase, la “instancia de clase” almacenada en :attr:`__self__` en realidad " "será la clase misma, de manera que invocar ya sea ``x.f(1)`` o ``C.f(1)`` es " "equivalente a invocar ``f(C,1)`` donde ``f`` es la función subyacente." #: ../Doc/reference/datamodel.rst:691 msgid "" "Note that the transformation from function object to instance method object " "happens each time the attribute is retrieved from the instance. In some " "cases, a fruitful optimization is to assign the attribute to a local " "variable and call that local variable. Also notice that this transformation " "only happens for user-defined functions; other callable objects (and all non-" "callable objects) are retrieved without transformation. It is also " "important to note that user-defined functions which are attributes of a " "class instance are not converted to bound methods; this *only* happens when " "the function is an attribute of the class." msgstr "" "Tome en cuenta que la transformación de objeto de función a objeto de método " "de instancia ocurre cada vez que el atributo es obtenido de la instancia. " "En algunos casos, una optimización fructífera es asignar el atributo a una " "variable local e invocarla. Note también que esta transformación únicamente " "ocurre con funciones definidas por usuario; otros objetos invocables (y " "todos los objetos no invocables) son obtenidos sin transformación. También " "es importante mencionar que las funciones definidas por el usuario, que son " "atributos de la instancia de una clase no son convertidos a métodos " "enlazados; esto ocurre *únicamente* cuando la función es un atributo de la " "clase." #: ../Doc/reference/datamodel.rst:704 msgid "Generator functions" msgstr "Funciones generadoras" #: ../Doc/reference/datamodel.rst:710 msgid "" "A function or method which uses the :keyword:`yield` statement (see section :" "ref:`yield`) is called a :dfn:`generator function`. Such a function, when " "called, always returns an :term:`iterator` object which can be used to " "execute the body of the function: calling the iterator's :meth:`iterator." "__next__` method will cause the function to execute until it provides a " "value using the :keyword:`!yield` statement. When the function executes a :" "keyword:`return` statement or falls off the end, a :exc:`StopIteration` " "exception is raised and the iterator will have reached the end of the set of " "values to be returned." msgstr "" "Una función o método que utiliza la instrucción :keyword:`yield` (consulte " "la sección :ref:`yield`) se denomina :dfn:`función generadora`. Una función " "de este tipo, cuando se llama, siempre retorna un objeto :term:`iterator` " "que se puede usar para ejecutar el cuerpo de la función: llamar al método :" "meth:`iterator.__next__` del iterador hará que la función se ejecute hasta " "que proporcione un valor usando la instrucción :keyword:`!yield`. Cuando la " "función ejecuta una instrucción :keyword:`return` o se sale del final, se " "genera una excepción :exc:`StopIteration` y el iterador habrá llegado al " "final del conjunto de valores que se retornarán." #: ../Doc/reference/datamodel.rst:722 msgid "Coroutine functions" msgstr "Funciones de corrutina" #: ../Doc/reference/datamodel.rst:727 msgid "" "A function or method which is defined using :keyword:`async def` is called " "a :dfn:`coroutine function`. Such a function, when called, returns a :term:" "`coroutine` object. It may contain :keyword:`await` expressions, as well " "as :keyword:`async with` and :keyword:`async for` statements. See also the :" "ref:`coroutine-objects` section." msgstr "" "Una función o método que es definido utilizando :keyword:`async def` se " "llama :dfn:`coroutine function`. Dicha función, cuando es invocada, retorna " "un objeto :term:`coroutine`. Éste puede contener expresiones :keyword:" "`await`, así como declaraciones :keyword:`async with` y :keyword:`async " "for`. Ver también la sección :ref:`coroutine-objects`." #: ../Doc/reference/datamodel.rst:735 msgid "Asynchronous generator functions" msgstr "Funciones generadoras asincrónicas" #: ../Doc/reference/datamodel.rst:741 msgid "" "A function or method which is defined using :keyword:`async def` and which " "uses the :keyword:`yield` statement is called a :dfn:`asynchronous generator " "function`. Such a function, when called, returns an :term:`asynchronous " "iterator` object which can be used in an :keyword:`async for` statement to " "execute the body of the function." msgstr "" "Una función o método que se define usando :keyword:`async def` y que usa la " "declaración :keyword:`yield` se llama :dfn:`función generadora asíncrona`. " "Una función de este tipo, cuando se llama, retorna un objeto :term:" "`asynchronous iterator` que se puede utilizar en una instrucción :keyword:" "`async for` para ejecutar el cuerpo de la función." #: ../Doc/reference/datamodel.rst:747 msgid "" "Calling the asynchronous iterator's :meth:`aiterator.__anext__ ` method will return an :term:`awaitable` which when awaited will " "execute until it provides a value using the :keyword:`yield` expression. " "When the function executes an empty :keyword:`return` statement or falls off " "the end, a :exc:`StopAsyncIteration` exception is raised and the " "asynchronous iterator will have reached the end of the set of values to be " "yielded." msgstr "" "Llamar al método :meth:`aiterator.__anext__ ` del iterador " "asíncrono retornará un :term:`awaitable` que, cuando se espere, se ejecutará " "hasta que proporcione un valor utilizando la expresión :keyword:`yield`. " "Cuando la función ejecuta una instrucción :keyword:`return` vacía o se sale " "del final, se genera una excepción :exc:`StopAsyncIteration` y el iterador " "asincrónico habrá llegado al final del conjunto de valores que se generarán." #: ../Doc/reference/datamodel.rst:758 msgid "Built-in functions" msgstr "Funciones incorporadas" #: ../Doc/reference/datamodel.rst:765 msgid "" "A built-in function object is a wrapper around a C function. Examples of " "built-in functions are :func:`len` and :func:`math.sin` (:mod:`math` is a " "standard built-in module). The number and type of the arguments are " "determined by the C function. Special read-only attributes: :attr:`__doc__` " "is the function's documentation string, or ``None`` if unavailable; :attr:" "`~definition.__name__` is the function's name; :attr:`__self__` is set to " "``None`` (but see the next item); :attr:`__module__` is the name of the " "module the function was defined in or ``None`` if unavailable." msgstr "" "Un objeto de función incorporada es un envoltorio (wrapper) alrededor de una " "función C. Ejemplos de funciones incorporadas son :func:`len` y :func:`math." "sin` (:mod:`math` es un módulo estándar incorporado). El número y tipo de " "argumentos son determinados por la función C. Atributos especiales de solo " "lectura: :attr:`__doc__` es la cadena de documentación de la función, o " "``None`` si no se encuentra disponible; :attr:`~definition.__name__` es el " "nombre de la función; :attr:`__init__` es establecido como ``None`` (sin " "embargo ver el siguiente elemento); :attr:`__module__` es el nombre del " "módulo en el que la función fue definida o ``None`` si no se encuentra " "disponible." #: ../Doc/reference/datamodel.rst:776 msgid "Built-in methods" msgstr "Métodos incorporados" #: ../Doc/reference/datamodel.rst:783 msgid "" "This is really a different disguise of a built-in function, this time " "containing an object passed to the C function as an implicit extra " "argument. An example of a built-in method is ``alist.append()``, assuming " "*alist* is a list object. In this case, the special read-only attribute :" "attr:`__self__` is set to the object denoted by *alist*." msgstr "" "Éste es realmente un disfraz distinto de una función incorporada, esta vez " "teniendo un objeto que se pasa a la función C como un argumento extra " "implícito. Un ejemplo de un método incorporado es ``alist.append()``, " "asumiendo que *alist* es un objeto de lista. En este caso, el atributo " "especial de solo lectura :attr:`__self__` es establecido al objeto indicado " "por *alist*." #: ../Doc/reference/datamodel.rst:791 msgid "Classes" msgstr "Clases" #: ../Doc/reference/datamodel.rst:793 msgid "" "Classes are callable. These objects normally act as factories for new " "instances of themselves, but variations are possible for class types that " "override :meth:`~object.__new__`. The arguments of the call are passed to :" "meth:`__new__` and, in the typical case, to :meth:`~object.__init__` to " "initialize the new instance." msgstr "" "Las clases son invocables. Estos objetos normalmente actúan como fábricas " "para nuevas instancias de sí mismos, pero son posibles variaciones para los " "tipos de clases que anulan :meth:`~object.__new__`. Los argumentos de la " "llamada se pasan a :meth:`__new__` y, en el caso típico, a :meth:`~object." "__init__` para inicializar la nueva instancia." #: ../Doc/reference/datamodel.rst:801 msgid "Class Instances" msgstr "Instancias de clases" #: ../Doc/reference/datamodel.rst:803 msgid "" "Instances of arbitrary classes can be made callable by defining a :meth:" "`~object.__call__` method in their class." msgstr "" "Las instancias de clases arbitrarias se pueden hacer invocables definiendo " "un método :meth:`~object.__call__` en su clase." #: ../Doc/reference/datamodel.rst:808 msgid "Modules" msgstr "Módulos" #: ../Doc/reference/datamodel.rst:814 msgid "" "Modules are a basic organizational unit of Python code, and are created by " "the :ref:`import system ` as invoked either by the :keyword:" "`import` statement, or by calling functions such as :func:`importlib." "import_module` and built-in :func:`__import__`. A module object has a " "namespace implemented by a dictionary object (this is the dictionary " "referenced by the ``__globals__`` attribute of functions defined in the " "module). Attribute references are translated to lookups in this dictionary, " "e.g., ``m.x`` is equivalent to ``m.__dict__[\"x\"]``. A module object does " "not contain the code object used to initialize the module (since it isn't " "needed once the initialization is done)." msgstr "" "Los módulos son una unidad básica organizacional en código Python, y son " "creados por el :ref:`import system ` al ser invocados ya sea " "por la declaración :keyword:`import`, o invocando funciones como :func:" "`importlib.import_module` y la incorporada :func:`__import__`. Un objeto de " "módulo tiene un espacio de nombres implementado por un objeto de diccionario " "(éste es el diccionario al que hace referencia el atributo de funciones " "``__globals__`` definido en el módulo). Las referencias de atributos son " "traducidas a búsquedas en este diccionario, p. ej., ``m.x`` es equivalente a " "``m.__dict__[“x”]``. Un objeto de módulo no contiene el objeto de código " "utilizado para iniciar el módulo (ya que no es necesario una vez que la " "inicialización es realizada)." #: ../Doc/reference/datamodel.rst:826 msgid "" "Attribute assignment updates the module's namespace dictionary, e.g., ``m.x " "= 1`` is equivalent to ``m.__dict__[\"x\"] = 1``." msgstr "" "La asignación de atributos actualiza el diccionario de espacio de nombres " "del módulo, p. ej., ``m.x = 1`` es equivalente a ``m.__dict__[“x”] = 1``." #: ../Doc/reference/datamodel.rst:836 msgid "Predefined (writable) attributes:" msgstr "Atributos predefinidos (escribibles):" #: ../Doc/reference/datamodel.rst:839 msgid ":attr:`__name__`" msgstr ":attr:`__name__`" #: ../Doc/reference/datamodel.rst:839 msgid "The module's name." msgstr "El nombre del módulo." #: ../Doc/reference/datamodel.rst:842 msgid "The module's documentation string, or ``None`` if unavailable." msgstr "" "El texto de documentación del módulo, o ``None`` si no está disponible." #: ../Doc/reference/datamodel.rst:852 msgid ":attr:`__file__`" msgstr ":attr:`__file__`" #: ../Doc/reference/datamodel.rst:846 msgid "" "The pathname of the file from which the module was loaded, if it was loaded " "from a file. The :attr:`__file__` attribute may be missing for certain types " "of modules, such as C modules that are statically linked into the " "interpreter. For extension modules loaded dynamically from a shared " "library, it's the pathname of the shared library file." msgstr "" "El nombre de ruta del archivo desde el que se cargó el módulo, si se cargó " "desde un archivo. El atributo :attr:`__file__` puede faltar para ciertos " "tipos de módulos, como los módulos C que están vinculados estáticamente al " "intérprete. Para los módulos de extensión cargados dinámicamente desde una " "biblioteca compartida, es el nombre de ruta del archivo de la biblioteca " "compartida." #: ../Doc/reference/datamodel.rst:855 msgid "" "A dictionary containing :term:`variable annotations ` " "collected during module body execution. For best practices on working with :" "attr:`__annotations__`, please see :ref:`annotations-howto`." msgstr "" "Un diccionario que contiene el :term:`variable annotations ` recopilados durante la ejecución del cuerpo del módulo. Para " "buenas prácticas sobre trabajar con :attr:`__annotations__`, por favor ve :" "ref:`annotations-howto`." #: ../Doc/reference/datamodel.rst:862 msgid "" "Special read-only attribute: :attr:`~object.__dict__` is the module's " "namespace as a dictionary object." msgstr "" "El atributo especial de solo lectura :attr:`~object.__dict__` es el espacio " "de nombres del módulo como un objeto de diccionario." #: ../Doc/reference/datamodel.rst:867 msgid "" "Because of the way CPython clears module dictionaries, the module dictionary " "will be cleared when the module falls out of scope even if the dictionary " "still has live references. To avoid this, copy the dictionary or keep the " "module around while using its dictionary directly." msgstr "" "Debido a la manera en la que CPython limpia los diccionarios de módulo, el " "diccionario de módulo será limpiado cuando el módulo se encuentra fuera de " "alcance, incluso si el diccionario aún tiene referencias existentes. Para " "evitar esto, copie el diccionario o mantenga el módulo cerca mientras usa el " "diccionario directamente." #: ../Doc/reference/datamodel.rst:874 msgid "Custom classes" msgstr "Clases personalizadas" #: ../Doc/reference/datamodel.rst:876 msgid "" "Custom class types are typically created by class definitions (see section :" "ref:`class`). A class has a namespace implemented by a dictionary object. " "Class attribute references are translated to lookups in this dictionary, e." "g., ``C.x`` is translated to ``C.__dict__[\"x\"]`` (although there are a " "number of hooks which allow for other means of locating attributes). When " "the attribute name is not found there, the attribute search continues in the " "base classes. This search of the base classes uses the C3 method resolution " "order which behaves correctly even in the presence of 'diamond' inheritance " "structures where there are multiple inheritance paths leading back to a " "common ancestor. Additional details on the C3 MRO used by Python can be " "found in the documentation accompanying the 2.3 release at https://www." "python.org/download/releases/2.3/mro/." msgstr "" "Los tipos de clases personalizadas son normalmente creadas por definiciones " "de clases (ver sección :ref:`class`). Una clase tiene implementado un " "espacio de nombres por un objeto de diccionario. Las referencias de " "atributos de clase son traducidas a búsquedas en este diccionario, p. ej., " "``C.x`` es traducido a ``C.__dict__[“x”]`` (aunque hay una serie de enlaces " "que permiten la ubicación de atributos por otros medios). Cuando el nombre " "de atributo no es encontrado ahí, la búsqueda de atributo continúa en las " "clases base. Esta búsqueda de las clases base utiliza la orden de resolución " "de métodos C3 que se comporta correctamente aún en la presencia de " "estructuras de herencia ‘diamante’ donde existen múltiples rutas de herencia " "que llevan a un ancestro común. Detalles adicionales en el MRO C3 utilizados " "por Python pueden ser encontrados en la documentación correspondiente a la " "versión 2.3 en https://www.python.org/download/releases/2.3/mro/." #: ../Doc/reference/datamodel.rst:900 msgid "" "When a class attribute reference (for class :class:`C`, say) would yield a " "class method object, it is transformed into an instance method object whose :" "attr:`__self__` attribute is :class:`C`. When it would yield a static " "method object, it is transformed into the object wrapped by the static " "method object. See section :ref:`descriptors` for another way in which " "attributes retrieved from a class may differ from those actually contained " "in its :attr:`~object.__dict__`." msgstr "" "Cuando la referencia de un atributo de clase (digamos, para la clase :class:" "`C`) produce un objeto de método de clase, éste es transformado a un objeto " "de método de instancia cuyo atributo :attr:`__self__` es :class:`C`. Cuando " "produce un objeto de un método estático, éste es transformado al objeto " "envuelto por el objeto de método estático. Ver sección :ref:`descriptors` " "para otra manera en la que los atributos obtenidos de una clase pueden " "diferir de los que en realidad están contenidos en su :attr:`~object." "__dict__`." #: ../Doc/reference/datamodel.rst:910 msgid "" "Class attribute assignments update the class's dictionary, never the " "dictionary of a base class." msgstr "" "Las asignaciones de atributos de clase actualizan el diccionario de la " "clase, nunca el diccionario de la clase base." #: ../Doc/reference/datamodel.rst:915 msgid "" "A class object can be called (see above) to yield a class instance (see " "below)." msgstr "" "Un objeto de clase puede ser invocado (ver arriba) para producir una " "instancia de clase (ver a continuación)." #: ../Doc/reference/datamodel.rst:929 msgid ":attr:`~definition.__name__`" msgstr ":attr:`~definition.__name__`" #: ../Doc/reference/datamodel.rst:929 msgid "The class name." msgstr "El nombre de la clase." #: ../Doc/reference/datamodel.rst:932 msgid "The name of the module in which the class was defined." msgstr "El nombre del módulo en el que se definió la clase." #: ../Doc/reference/datamodel.rst:935 msgid "The dictionary containing the class's namespace." msgstr "El diccionario conteniendo el espacio de nombres de la clase." #: ../Doc/reference/datamodel.rst:939 msgid ":attr:`~class.__bases__`" msgstr ":attr:`~class.__bases__`" #: ../Doc/reference/datamodel.rst:938 msgid "" "A tuple containing the base classes, in the order of their occurrence in the " "base class list." msgstr "" "Una tupla conteniendo las clases de base, en orden de ocurrencia en la lista " "de clase base." #: ../Doc/reference/datamodel.rst:942 msgid "The class's documentation string, or ``None`` if undefined." msgstr "" "El texto de documentación de la clase, o ``None`` si no está disponible." #: ../Doc/reference/datamodel.rst:945 msgid "" "A dictionary containing :term:`variable annotations ` " "collected during class body execution. For best practices on working with :" "attr:`__annotations__`, please see :ref:`annotations-howto`." msgstr "" "Un diccionario conteniendo el :term:`variable annotations ` recopilados durante la ejecución del cuerpo de la clase. Para " "buenas prácticas sobre trabajar con :attr:`__annotations__`, por favor ve :" "ref:`annotations-howto`." #: ../Doc/reference/datamodel.rst:952 msgid "" "A tuple containing the :ref:`type parameters ` of a :ref:" "`generic class `." msgstr "" "Una tupla que contiene el :ref:`type parameters ` de un :ref:" "`generic class `." #: ../Doc/reference/datamodel.rst:957 msgid "Class instances" msgstr "Instancias de clase" #: ../Doc/reference/datamodel.rst:965 msgid "" "A class instance is created by calling a class object (see above). A class " "instance has a namespace implemented as a dictionary which is the first " "place in which attribute references are searched. When an attribute is not " "found there, and the instance's class has an attribute by that name, the " "search continues with the class attributes. If a class attribute is found " "that is a user-defined function object, it is transformed into an instance " "method object whose :attr:`__self__` attribute is the instance. Static " "method and class method objects are also transformed; see above under " "\"Classes\". See section :ref:`descriptors` for another way in which " "attributes of a class retrieved via its instances may differ from the " "objects actually stored in the class's :attr:`~object.__dict__`. If no " "class attribute is found, and the object's class has a :meth:`~object." "__getattr__` method, that is called to satisfy the lookup." msgstr "" "Una instancia de clase se crea llamando a un objeto de clase (ver arriba). " "Una instancia de clase tiene un espacio de nombres implementado como un " "diccionario, que es el primer lugar en el que se buscan las referencias de " "atributos. Cuando no se encuentra un atributo allí y la clase de la " "instancia tiene un atributo con ese nombre, la búsqueda continúa con los " "atributos de la clase. Si se encuentra un atributo de clase que es un objeto " "de función definido por el usuario, se transforma en un objeto de método de " "instancia cuyo atributo :attr:`__self__` es la instancia. Los objetos de " "métodos estáticos y de clases también se transforman; consulte más arriba en " "\"Clases\". Consulte la sección :ref:`descriptors` para conocer otra forma " "en la que los atributos de una clase recuperados a través de sus instancias " "pueden diferir de los objetos realmente almacenados en el :attr:`~object." "__dict__` de la clase. Si no se encuentra ningún atributo de clase y la " "clase del objeto tiene un método :meth:`~object.__getattr__`, se llama para " "satisfacer la búsqueda." #: ../Doc/reference/datamodel.rst:981 msgid "" "Attribute assignments and deletions update the instance's dictionary, never " "a class's dictionary. If the class has a :meth:`~object.__setattr__` or :" "meth:`~object.__delattr__` method, this is called instead of updating the " "instance dictionary directly." msgstr "" "Las asignaciones y eliminaciones de atributos actualizan el diccionario de " "la instancia, nunca el diccionario de una clase. Si la clase tiene un " "método :meth:`~object.__setattr__` o :meth:`~object.__delattr__`, se llama a " "este en lugar de actualizar el diccionario de instancia directamente." #: ../Doc/reference/datamodel.rst:991 msgid "" "Class instances can pretend to be numbers, sequences, or mappings if they " "have methods with certain special names. See section :ref:`specialnames`." msgstr "" "Instancias de clases pueden pretender ser números, secuencias o mapeos si " "tienen métodos con ciertos nombres especiales. Ver sección :ref:" "`specialnames`." #: ../Doc/reference/datamodel.rst:998 msgid "" "Special attributes: :attr:`~object.__dict__` is the attribute dictionary; :" "attr:`~instance.__class__` is the instance's class." msgstr "" "Atributos especiales: :attr:`~object.__dict__` es el diccionario de " "atributos; :attr:`~instance.__class__` es la clase de la instancia." #: ../Doc/reference/datamodel.rst:1003 msgid "I/O objects (also known as file objects)" msgstr "Objetos E/S (también conocidos como objetos de archivo)" #: ../Doc/reference/datamodel.rst:1018 msgid "" "A :term:`file object` represents an open file. Various shortcuts are " "available to create file objects: the :func:`open` built-in function, and " "also :func:`os.popen`, :func:`os.fdopen`, and the :meth:`~socket.socket." "makefile` method of socket objects (and perhaps by other functions or " "methods provided by extension modules)." msgstr "" "Un :term:`file object` representa un archivo abierto. Diversos accesos " "directos se encuentran disponibles para crear objetos de archivo: la función " "incorporada :func:`open`, así como :func:`os.popen`, :func:`os.fdopen`, y el " "método de objetos socket :meth:`~socket.makefile` (y quizás por otras " "funciones y métodos proporcionados por módulos de extensión)." #: ../Doc/reference/datamodel.rst:1024 msgid "" "The objects ``sys.stdin``, ``sys.stdout`` and ``sys.stderr`` are initialized " "to file objects corresponding to the interpreter's standard input, output " "and error streams; they are all open in text mode and therefore follow the " "interface defined by the :class:`io.TextIOBase` abstract class." msgstr "" "Los objetos ``sys.stdin``, ``sys.stdout`` y ``sys.stderr`` son iniciados a " "objetos de archivos correspondientes a la entrada y salida estándar del " "intérprete, así como flujos de error; todos ellos están abiertos en el modo " "de texto y por lo tanto siguen la interface definida por la clase abstracta :" "class:`io.TextIOBase`." #: ../Doc/reference/datamodel.rst:1032 msgid "Internal types" msgstr "Tipos internos" #: ../Doc/reference/datamodel.rst:1038 msgid "" "A few types used internally by the interpreter are exposed to the user. " "Their definitions may change with future versions of the interpreter, but " "they are mentioned here for completeness." msgstr "" "Algunos tipos utilizados internamente por el intérprete son expuestos al " "usuario. Sus definiciones pueden cambiar en futuras versiones del " "intérprete, pero son mencionadas aquí para complementar." #: ../Doc/reference/datamodel.rst:1046 msgid "Code objects" msgstr "Objetos de código" #: ../Doc/reference/datamodel.rst:1050 msgid "" "Code objects represent *byte-compiled* executable Python code, or :term:" "`bytecode`. The difference between a code object and a function object is " "that the function object contains an explicit reference to the function's " "globals (the module in which it was defined), while a code object contains " "no context; also the default argument values are stored in the function " "object, not in the code object (because they represent values calculated at " "run-time). Unlike function objects, code objects are immutable and contain " "no references (directly or indirectly) to mutable objects." msgstr "" "Los objetos de código representan código de Python ejecutable *compilado por " "bytes*, o :term:`bytecode`. La diferencia entre un objeto de código y un " "objeto de función es que el objeto de función contiene una referencia " "explícita a los globales de la función (el módulo en el que fue definido), " "mientras el objeto de código no contiene contexto; de igual manera los " "valores por defecto de los argumentos son almacenados en el objeto de " "función, no en el objeto de código (porque representan valores calculados en " "tiempo de ejecución). A diferencia de objetos de función, los objetos de " "código son inmutables y no contienen referencias (directas o indirectas) a " "objetos mutables." #: ../Doc/reference/datamodel.rst:1078 msgid "" "Special read-only attributes: :attr:`co_name` gives the function name; :attr:" "`co_qualname` gives the fully qualified function name; :attr:`co_argcount` " "is the total number of positional arguments (including positional-only " "arguments and arguments with default values); :attr:`co_posonlyargcount` is " "the number of positional-only arguments (including arguments with default " "values); :attr:`co_kwonlyargcount` is the number of keyword-only arguments " "(including arguments with default values); :attr:`co_nlocals` is the number " "of local variables used by the function (including arguments); :attr:" "`co_varnames` is a tuple containing the names of the local variables " "(starting with the argument names); :attr:`co_cellvars` is a tuple " "containing the names of local variables that are referenced by nested " "functions; :attr:`co_freevars` is a tuple containing the names of free " "variables; :attr:`co_code` is a string representing the sequence of bytecode " "instructions; :attr:`co_consts` is a tuple containing the literals used by " "the bytecode; :attr:`co_names` is a tuple containing the names used by the " "bytecode; :attr:`co_filename` is the filename from which the code was " "compiled; :attr:`co_firstlineno` is the first line number of the function; :" "attr:`co_lnotab` is a string encoding the mapping from bytecode offsets to " "line numbers (for details see the source code of the interpreter, is " "deprecated since 3.12 and may be removed in 3.14); :attr:`co_stacksize` is " "the required stack size; :attr:`co_flags` is an integer encoding a number of " "flags for the interpreter." msgstr "" "Atributos especiales de solo lectura: :attr:`co_name` proporciona el nombre " "de la función; :attr:`co_qualname` proporciona el nombre completo de la " "función; :attr:`co_argcount` es el número total de argumentos posicionales " "(incluidos los argumentos solo posicionales y los argumentos con valores " "predeterminados); :attr:`co_posonlyargcount` es el número de argumentos solo " "posicionales (incluidos los argumentos con valores predeterminados); :attr:" "`co_kwonlyargcount` es el número de argumentos de solo palabras clave " "(incluidos los argumentos con valores predeterminados); :attr:`co_nlocals` " "es el número de variables locales utilizadas por la función (incluidos los " "argumentos); :attr:`co_varnames` es una tupla que contiene los nombres de " "las variables locales (comenzando con los nombres de los argumentos); :attr:" "`co_cellvars` es una tupla que contiene los nombres de las variables locales " "a las que hacen referencia las funciones anidadas; :attr:`co_freevars` es " "una tupla que contiene los nombres de las variables libres; :attr:`co_code` " "es una cadena que representa la secuencia de instrucciones de código de " "bytes; :attr:`co_consts` es una tupla que contiene los literales utilizados " "por el código de bytes; :attr:`co_names` es una tupla que contiene los " "nombres utilizados por el código de bytes; :attr:`co_filename` es el nombre " "del archivo a partir del cual se compiló el código; :attr:`co_firstlineno` " "es el número de primera línea de la función; :attr:`co_lnotab` es una cadena " "que codifica la asignación de desplazamientos de código de bytes a números " "de línea (para obtener más detalles, consulte el código fuente del " "intérprete, está en desuso desde 3.12 y puede eliminarse en 3.14); :attr:" "`co_stacksize` es el tamaño de pila requerido; :attr:`co_flags` es un número " "entero que codifica una serie de indicadores para el intérprete." #: ../Doc/reference/datamodel.rst:1104 msgid "" "The following flag bits are defined for :attr:`co_flags`: bit ``0x04`` is " "set if the function uses the ``*arguments`` syntax to accept an arbitrary " "number of positional arguments; bit ``0x08`` is set if the function uses the " "``**keywords`` syntax to accept arbitrary keyword arguments; bit ``0x20`` is " "set if the function is a generator." msgstr "" "Los siguientes bits de bandera son definidos por :attr:`co_flags` : bit " "``0x04`` es establecido si la función utiliza la sintaxis ``*arguments`` " "para aceptar un número arbitrario de argumentos posicionales; bit ``0x08`` " "es establecido si la función utiliza la sintaxis ``**keywords`` para aceptar " "argumentos de palabras clave arbitrarios; bit ``0x20`` es establecido si la " "función es un generador." #: ../Doc/reference/datamodel.rst:1110 msgid "" "Future feature declarations (``from __future__ import division``) also use " "bits in :attr:`co_flags` to indicate whether a code object was compiled with " "a particular feature enabled: bit ``0x2000`` is set if the function was " "compiled with future division enabled; bits ``0x10`` and ``0x1000`` were " "used in earlier versions of Python." msgstr "" "Declaraciones de características futuras (``from __future__ import " "division``) también utiliza bits en :attr:`co_flags` para indicar si el " "objeto de código fue compilado con alguna característica particular " "habilitada: el bit ``0x2000`` es establecido si la función fue compilada con " "división futura habilitada; los bits ``0x10`` y ``0x1000`` fueron utilizados " "en versiones previas de Python." #: ../Doc/reference/datamodel.rst:1116 msgid "Other bits in :attr:`co_flags` are reserved for internal use." msgstr "Otros bits en :attr:`co_flags` son reservados para uso interno." #: ../Doc/reference/datamodel.rst:1120 msgid "" "If a code object represents a function, the first item in :attr:`co_consts` " "is the documentation string of the function, or ``None`` if undefined." msgstr "" "Si un objeto de código representa una función, el primer elemento en :attr:" "`co_consts` es la cadena de documentación de la función, o ``None`` si no " "está definido." #: ../Doc/reference/datamodel.rst:1125 msgid "" "Returns an iterable over the source code positions of each bytecode " "instruction in the code object." msgstr "" "Retorna un iterable sobre las posiciones del código fuente de cada " "instrucción de código de bytes en el objeto de código." #: ../Doc/reference/datamodel.rst:1128 msgid "" "The iterator returns tuples containing the ``(start_line, end_line, " "start_column, end_column)``. The *i-th* tuple corresponds to the position of " "the source code that compiled to the *i-th* instruction. Column information " "is 0-indexed utf-8 byte offsets on the given source line." msgstr "" "El iterador retorna tuplas que contienen ``(start_line, end_line, " "start_column, end_column)``. La tupla *i-th* corresponde a la posición del " "código fuente que se compiló en la instrucción *i-th*. La información de la " "columna son compensaciones de utf-8 bytes indexadas en 0 en la línea de " "origen dada." #: ../Doc/reference/datamodel.rst:1134 msgid "" "This positional information can be missing. A non-exhaustive lists of cases " "where this may happen:" msgstr "" "Esta información posicional puede faltar. Una lista no exhaustiva de casos " "en los que esto puede suceder:" #: ../Doc/reference/datamodel.rst:1137 msgid "Running the interpreter with :option:`-X` ``no_debug_ranges``." msgstr "Ejecutando el intérprete con :option:`-X` ``no_debug_ranges``." #: ../Doc/reference/datamodel.rst:1138 msgid "" "Loading a pyc file compiled while using :option:`-X` ``no_debug_ranges``." msgstr "" "Cargando un archivo pyc compilado usando :option:`-X` ``no_debug_ranges``." #: ../Doc/reference/datamodel.rst:1139 msgid "Position tuples corresponding to artificial instructions." msgstr "Tuplas de posición correspondientes a instrucciones artificiales." #: ../Doc/reference/datamodel.rst:1140 msgid "" "Line and column numbers that can't be represented due to implementation " "specific limitations." msgstr "" "Números de línea y columna que no se pueden representar debido a " "limitaciones específicas de la implementación." #: ../Doc/reference/datamodel.rst:1143 msgid "" "When this occurs, some or all of the tuple elements can be :const:`None`." msgstr "" "Cuando esto ocurre, algunos o todos los elementos de la tupla pueden ser :" "const:`None`." #: ../Doc/reference/datamodel.rst:1149 msgid "" "This feature requires storing column positions in code objects which may " "result in a small increase of disk usage of compiled Python files or " "interpreter memory usage. To avoid storing the extra information and/or " "deactivate printing the extra traceback information, the :option:`-X` " "``no_debug_ranges`` command line flag or the :envvar:`PYTHONNODEBUGRANGES` " "environment variable can be used." msgstr "" "Esta función requiere el almacenamiento de posiciones de columna en objetos " "de código, lo que puede resultar en un pequeño aumento del uso del disco de " "archivos de Python compilados o del uso de la memoria del intérprete. Para " "evitar almacenar la información extra y/o desactivar la impresión de la " "información extra de seguimiento, se puede usar el indicador de línea de " "comando :option:`-X` ``no_debug_ranges`` o la variable de entorno :envvar:" "`PYTHONNODEBUGRANGES`." #: ../Doc/reference/datamodel.rst:1160 msgid "Frame objects" msgstr "Objetos de marco" #: ../Doc/reference/datamodel.rst:1164 msgid "" "Frame objects represent execution frames. They may occur in traceback " "objects (see below), and are also passed to registered trace functions." msgstr "" "Los objetos de marco representan marcos de ejecución. Pueden ocurrir en " "objetos de rastreo (ver a continuación), y son también pasados hacia " "funciones de rastreo registradas." #: ../Doc/reference/datamodel.rst:1175 msgid "" "Special read-only attributes: :attr:`f_back` is to the previous stack frame " "(towards the caller), or ``None`` if this is the bottom stack frame; :attr:" "`f_code` is the code object being executed in this frame; :attr:`f_locals` " "is the dictionary used to look up local variables; :attr:`f_globals` is used " "for global variables; :attr:`f_builtins` is used for built-in (intrinsic) " "names; :attr:`f_lasti` gives the precise instruction (this is an index into " "the bytecode string of the code object)." msgstr "" "Atributos especiales de solo lectura: :attr:`f_back` es para el marco de " "pila anterior (hacia quien produce el llamado), o ``None`` si éste es el " "marco de pila inferior; :attr:`f_code` es el objeto de código ejecutado en " "este marco; :attr:`f_locals` es el diccionario utilizado para buscar " "variables locales; :attr:`f_globals` es usado por las variables globales; :" "attr:`f_builtins` es utilizado por nombres incorporados (intrínsecos); :attr:" "`f_lasti` da la instrucción precisa (éste es un índice dentro de la cadena " "de bytecode del objeto de código)." #: ../Doc/reference/datamodel.rst:1183 msgid "" "Accessing ``f_code`` raises an :ref:`auditing event ` ``object." "__getattr__`` with arguments ``obj`` and ``\"f_code\"``." msgstr "" "Acceder a ``f_code`` lanza un objeto :ref:`evento de auditoría ` " "``.__getattr__`` con argumentos ``obj`` y ``\"f_code\"`` ." #: ../Doc/reference/datamodel.rst:1192 msgid "" "Special writable attributes: :attr:`f_trace`, if not ``None``, is a function " "called for various events during code execution (this is used by the " "debugger). Normally an event is triggered for each new source line - this " "can be disabled by setting :attr:`f_trace_lines` to :const:`False`." msgstr "" "Atributos especiales escribibles: :attr:`f_trace`, de lo contrario ``None``, " "es una función llamada por distintos eventos durante la ejecución del código " "(éste es utilizado por el depurador). Normalmente un evento es desencadenado " "por cada una de las líneas fuente - esto puede ser deshabilitado " "estableciendo :attr:`f_trace_lines` a :const:`False`." #: ../Doc/reference/datamodel.rst:1197 msgid "" "Implementations *may* allow per-opcode events to be requested by setting :" "attr:`f_trace_opcodes` to :const:`True`. Note that this may lead to " "undefined interpreter behaviour if exceptions raised by the trace function " "escape to the function being traced." msgstr "" "Las implementaciones *pueden* permitir que eventos por código de operación " "sean solicitados estableciendo :attr:`f_trace_opcodes` a :const:`True`. " "Tenga en cuenta que esto puede llevar a un comportamiento indefinido del " "intérprete si se levantan excepciones por la función de rastreo escape hacia " "la función que está siendo rastreada." #: ../Doc/reference/datamodel.rst:1202 msgid "" ":attr:`f_lineno` is the current line number of the frame --- writing to this " "from within a trace function jumps to the given line (only for the bottom-" "most frame). A debugger can implement a Jump command (aka Set Next " "Statement) by writing to f_lineno." msgstr "" ":attr:`f_lineno` es el número de línea actual del marco --- escribiendo a " "esta forma dentro de una función de rastreo salta a la línea dada (solo para " "el último marco). Un depurador puede implementar un comando de salto " "(*Jump*) (también conocido como *Set Next Statement*) al escribir en " "f_lineno." #: ../Doc/reference/datamodel.rst:1207 msgid "Frame objects support one method:" msgstr "Objetos de marco soportan un método:" #: ../Doc/reference/datamodel.rst:1211 msgid "" "This method clears all references to local variables held by the frame. " "Also, if the frame belonged to a generator, the generator is finalized. " "This helps break reference cycles involving frame objects (for example when " "catching an exception and storing its traceback for later use)." msgstr "" "Este método limpia todas las referencias a variables locales mantenidas por " "el marco. También, si el marco pertenecía a un generador, éste es " "finalizado. Esto ayuda a interrumpir los ciclos de referencia que involucran " "objetos de marco (por ejemplo al detectar una excepción y almacenando su " "rastro para uso posterior)." #: ../Doc/reference/datamodel.rst:1217 msgid ":exc:`RuntimeError` is raised if the frame is currently executing." msgstr ":exc:`RuntimeError` es lanzado si el marco se encuentra en ejecución." #: ../Doc/reference/datamodel.rst:1225 msgid "Traceback objects" msgstr "Objetos de seguimiento de pila (traceback)" #: ../Doc/reference/datamodel.rst:1238 msgid "" "Traceback objects represent a stack trace of an exception. A traceback " "object is implicitly created when an exception occurs, and may also be " "explicitly created by calling :class:`types.TracebackType`." msgstr "" "Los objetos de seguimiento de pila representan el trazo de pila (*stack " "trace*) de una excepción. Un objeto de rastreo es creado de manera implícita " "cuando se da una excepción, y puede ser creada de manera explícita al " "llamar :class:`types.TracebackType`." #: ../Doc/reference/datamodel.rst:1242 msgid "" "For implicitly created tracebacks, when the search for an exception handler " "unwinds the execution stack, at each unwound level a traceback object is " "inserted in front of the current traceback. When an exception handler is " "entered, the stack trace is made available to the program. (See section :ref:" "`try`.) It is accessible as the third item of the tuple returned by ``sys." "exc_info()``, and as the ``__traceback__`` attribute of the caught exception." msgstr "" "Para seguimientos de pila (tracebacks) creados de manera implícita, cuando " "la búsqueda por un manejo de excepciones desenvuelve la pila de ejecución, " "en cada nivel de desenvolvimiento se inserta un objeto de rastreo al frente " "del rastreo actual. Cuando se entra a un manejo de excepción, la pila de " "rastreo se vuelve disponible para el programa. (Ver sección :ref:`try`.) Es " "accesible como el tercer elemento de la tupla retornada por ``sys." "exc_info()``, y como el atributo ``__traceback__`` de la excepción capturada." #: ../Doc/reference/datamodel.rst:1250 msgid "" "When the program contains no suitable handler, the stack trace is written " "(nicely formatted) to the standard error stream; if the interpreter is " "interactive, it is also made available to the user as ``sys.last_traceback``." msgstr "" "Cuando el programa no contiene un gestor apropiado, el trazo de pila es " "escrito (muy bien formateado) a la secuencia de error estándar; si el " "intérprete es interactivo, también se vuelve disponible al usuario como " "``sys.last_traceback``." #: ../Doc/reference/datamodel.rst:1255 msgid "" "For explicitly created tracebacks, it is up to the creator of the traceback " "to determine how the ``tb_next`` attributes should be linked to form a full " "stack trace." msgstr "" "Para seguimientos de pila creados de forma explícita, depende de su creador " "determinar cómo los atributos ``tb_next`` deberían ser ligados para formar " "un trazo de pila completo (*full stack trace*)." #: ../Doc/reference/datamodel.rst:1265 msgid "" "Special read-only attributes: :attr:`tb_frame` points to the execution frame " "of the current level; :attr:`tb_lineno` gives the line number where the " "exception occurred; :attr:`tb_lasti` indicates the precise instruction. The " "line number and last instruction in the traceback may differ from the line " "number of its frame object if the exception occurred in a :keyword:`try` " "statement with no matching except clause or with a finally clause." msgstr "" "Atributos especiales de solo lectura: :attr:`tb_frame` apunta al marco de " "ejecución del nivel actual; :attr:`tb_lineno` da el número de línea donde " "ocurrió la excepción; :attr:`tb_lasti` indica la instrucción precisa. El " "número de línea y la última instrucción en el seguimiento de pila puede " "diferir del número de línea de su objeto de marco si la excepción ocurrió en " "una declaración :keyword:`try` sin una cláusula de excepción (except) " "correspondiente o con una cláusula *finally*." #: ../Doc/reference/datamodel.rst:1274 msgid "" "Accessing ``tb_frame`` raises an :ref:`auditing event ` ``object." "__getattr__`` with arguments ``obj`` and ``\"tb_frame\"``." msgstr "" "Acceder a ``tb_frame`` lanza un objeto :ref:`evento de auditoría ` " "``.__getattr__`` con argumentos ``obj`` y ``tb_frame``." #: ../Doc/reference/datamodel.rst:1280 msgid "" "Special writable attribute: :attr:`tb_next` is the next level in the stack " "trace (towards the frame where the exception occurred), or ``None`` if there " "is no next level." msgstr "" "Atributo especial escribible: :attr:`tb_next` es el siguiente nivel en el " "trazo de pila (hacia el marco en donde ocurrió la excepción), o ``None`` si " "no existe un siguiente nivel." #: ../Doc/reference/datamodel.rst:1284 msgid "" "Traceback objects can now be explicitly instantiated from Python code, and " "the ``tb_next`` attribute of existing instances can be updated." msgstr "" "Los objetos de seguimiento de pila ya pueden ser instanciados de manera " "explícita desde código de Python, y el atributo ``tb_next`` de instancias " "existentes puede ser actualizado." #: ../Doc/reference/datamodel.rst:1290 msgid "Slice objects" msgstr "Objetos de segmento (Slice objects)" #: ../Doc/reference/datamodel.rst:1294 msgid "" "Slice objects are used to represent slices for :meth:`~object.__getitem__` " "methods. They are also created by the built-in :func:`slice` function." msgstr "" "Los objetos de sector se utilizan para representar sectores para métodos :" "meth:`~object.__getitem__`. También son creados por la función integrada :" "func:`slice`." #: ../Doc/reference/datamodel.rst:1303 msgid "" "Special read-only attributes: :attr:`~slice.start` is the lower bound; :attr:" "`~slice.stop` is the upper bound; :attr:`~slice.step` is the step value; " "each is ``None`` if omitted. These attributes can have any type." msgstr "" "Atributos especiales de solo lectura: :attr:`~slice.start` es el límite " "inferior; :attr:`~slice.stop` es el límite superior; :attr:`~slice.step` es " "el valor de paso; cada uno es ``None`` si es omitido. Estos atributos pueden " "ser de cualquier tipo." #: ../Doc/reference/datamodel.rst:1307 msgid "Slice objects support one method:" msgstr "Los objetos de segmento soportan un método:" #: ../Doc/reference/datamodel.rst:1311 msgid "" "This method takes a single integer argument *length* and computes " "information about the slice that the slice object would describe if applied " "to a sequence of *length* items. It returns a tuple of three integers; " "respectively these are the *start* and *stop* indices and the *step* or " "stride length of the slice. Missing or out-of-bounds indices are handled in " "a manner consistent with regular slices." msgstr "" "Este método toma un argumento *length* de entero simple y calcula " "información relacionada con el segmento que el mismo describiría si fuera " "aplicado a una secuencia de elementos *length*. Retorna una tupla de tres " "enteros; respectivamente estos son los índices *start* y *stop* y el *step* " "o longitud del paso del segmento. Índices faltantes o fuera de los límites " "son manipulados de manera consistente con segmentos regulares." #: ../Doc/reference/datamodel.rst:1320 msgid "Static method objects" msgstr "Objetos de método estático" #: ../Doc/reference/datamodel.rst:1322 msgid "" "Static method objects provide a way of defeating the transformation of " "function objects to method objects described above. A static method object " "is a wrapper around any other object, usually a user-defined method object. " "When a static method object is retrieved from a class or a class instance, " "the object actually returned is the wrapped object, which is not subject to " "any further transformation. Static method objects are also callable. Static " "method objects are created by the built-in :func:`staticmethod` constructor." msgstr "" "Los objetos de método estático proveen una forma de anular la transformación " "de objetos de función a objetos de método descritos anteriormente. Un objeto " "de método estático es una envoltura (*wrapper*) alrededor de cualquier otro " "objeto, usualmente un objeto de método definido por usuario. Cuando un " "objeto de método estático es obtenido desde una clase o una instancia de " "clase, usualmente el objeto retornado es el objeto envuelto, el cual no está " "objeto a ninguna transformación adicional. Los objetos de método estático " "también pueden ser llamados. Los objetos de método estático son creados por " "el constructor incorporado :func:`staticmethod`." #: ../Doc/reference/datamodel.rst:1332 msgid "Class method objects" msgstr "Objetos de método de clase" #: ../Doc/reference/datamodel.rst:1334 msgid "" "A class method object, like a static method object, is a wrapper around " "another object that alters the way in which that object is retrieved from " "classes and class instances. The behaviour of class method objects upon such " "retrieval is described above, under \"User-defined methods\". Class method " "objects are created by the built-in :func:`classmethod` constructor." msgstr "" "Un objeto de método de clase, igual que un objeto de método estático, es un " "envoltorio (wrapper) alrededor de otro objeto que altera la forma en la que " "el objeto es obtenido desde las clases y las instancias de clase. El " "comportamiento de los objetos de método de clase sobre tal obtención es " "descrita más arriba, debajo de “Métodos definidos por usuario”. Objetos de " "clase de método son creados por el constructor incorporado :func:" "`classmethod`." #: ../Doc/reference/datamodel.rst:1344 msgid "Special method names" msgstr "Nombres especiales de método" #: ../Doc/reference/datamodel.rst:1350 msgid "" "A class can implement certain operations that are invoked by special syntax " "(such as arithmetic operations or subscripting and slicing) by defining " "methods with special names. This is Python's approach to :dfn:`operator " "overloading`, allowing classes to define their own behavior with respect to " "language operators. For instance, if a class defines a method named :meth:" "`~object.__getitem__`, and ``x`` is an instance of this class, then ``x[i]`` " "is roughly equivalent to ``type(x).__getitem__(x, i)``. Except where " "mentioned, attempts to execute an operation raise an exception when no " "appropriate method is defined (typically :exc:`AttributeError` or :exc:" "`TypeError`)." msgstr "" "Una clase puede implementar ciertas operaciones que se invocan mediante una " "sintaxis especial (como operaciones aritméticas o subíndices y divisiones) " "definiendo métodos con nombres especiales. Este es el enfoque de Python " "para :dfn:`sobrecarga de operadores`, permitiendo a las clases definir su " "propio comportamiento con respecto a los operadores del lenguaje. Por " "ejemplo, si una clase define un método denominado :meth:`~object." "__getitem__` y ``x`` es una instancia de esta clase, entonces ``x[i]`` es " "aproximadamente equivalente a ``type(x).__getitem__(x, i)``. Excepto donde " "se mencione, los intentos de ejecutar una operación generan una excepción " "cuando no se define ningún método apropiado (normalmente :exc:" "`AttributeError` o :exc:`TypeError`)." #: ../Doc/reference/datamodel.rst:1361 msgid "" "Setting a special method to ``None`` indicates that the corresponding " "operation is not available. For example, if a class sets :meth:`~object." "__iter__` to ``None``, the class is not iterable, so calling :func:`iter` on " "its instances will raise a :exc:`TypeError` (without falling back to :meth:" "`~object.__getitem__`). [#]_" msgstr "" "Establecer un método especial en ``None`` indica que la operación " "correspondiente no está disponible. Por ejemplo, si una clase establece :" "meth:`~object.__iter__` en ``None``, la clase no es iterable, por lo que " "llamar a :func:`iter` en sus instancias generará un :exc:`TypeError` (sin " "recurrir a :meth:`~object.__getitem__`). [#]_" #: ../Doc/reference/datamodel.rst:1367 msgid "" "When implementing a class that emulates any built-in type, it is important " "that the emulation only be implemented to the degree that it makes sense for " "the object being modelled. For example, some sequences may work well with " "retrieval of individual elements, but extracting a slice may not make " "sense. (One example of this is the :class:`~xml.dom.NodeList` interface in " "the W3C's Document Object Model.)" msgstr "" "Cuando se implementa una clase que emula cualquier tipo incorporado, es " "importante que la emulación solo sea implementado al grado que hace sentido " "para el objeto que está siendo modelado. Por ejemplo, algunas secuencias " "pueden trabajar bien con la obtención de elementos individuales, pero " "extraer un segmento puede no tener mucho sentido. (Un ejemplo de esto es la " "interfaz :class:`~xml.dom.NodeList`, en el Modelo de Objetos del Documento " "del W3C.)" #: ../Doc/reference/datamodel.rst:1378 msgid "Basic customization" msgstr "Personalización básica" #: ../Doc/reference/datamodel.rst:1384 msgid "" "Called to create a new instance of class *cls*. :meth:`__new__` is a static " "method (special-cased so you need not declare it as such) that takes the " "class of which an instance was requested as its first argument. The " "remaining arguments are those passed to the object constructor expression " "(the call to the class). The return value of :meth:`__new__` should be the " "new object instance (usually an instance of *cls*)." msgstr "" "Es llamado para crear una nueva instancia de clase *cls*. :meth:`__new__` es " "un método estático (como un caso especial, así que no se necesita declarar " "como tal) que toma la clase de donde fue solicitada una instancia como su " "primer argumento. Los argumentos restantes son aquellos que se pasan a la " "expresión del constructor de objetos (para llamar a la clase). El valor " "retornado de :meth:`__new__` deberá ser la nueva instancia de objeto " "(normalmente una instancia de *cls*)." #: ../Doc/reference/datamodel.rst:1391 msgid "" "Typical implementations create a new instance of the class by invoking the " "superclass's :meth:`__new__` method using ``super().__new__(cls[, ...])`` " "with appropriate arguments and then modifying the newly created instance as " "necessary before returning it." msgstr "" "Las implementaciones típicas crean una nueva instancia de la clase invocando " "el método :meth:`__new__` de la superclase usando ``super()." "__new__(cls[, ...])`` con los argumentos apropiados y luego modificando la " "instancia recién creada según sea necesario antes de retornarla." #: ../Doc/reference/datamodel.rst:1396 msgid "" "If :meth:`__new__` is invoked during object construction and it returns an " "instance of *cls*, then the new instance’s :meth:`__init__` method will be " "invoked like ``__init__(self[, ...])``, where *self* is the new instance and " "the remaining arguments are the same as were passed to the object " "constructor." msgstr "" "Si :meth:`__new__` es invocado durante la construcción del objeto y éste " "retorna una instancia de *cls*, entonces el nuevo método :meth:`__init__` de " "la instancia será invocado como ``__init__(self[, …])``, donde *self* es la " "nueva instancia y los argumentos restantes son iguales a como fueron pasados " "hacia el constructor de objetos." #: ../Doc/reference/datamodel.rst:1401 msgid "" "If :meth:`__new__` does not return an instance of *cls*, then the new " "instance's :meth:`__init__` method will not be invoked." msgstr "" "Si :meth:`__new__` no retorna una instancia de *cls*, entonces el nuevo " "método :meth:`__init__` de la instancia no será invocado." #: ../Doc/reference/datamodel.rst:1404 msgid "" ":meth:`__new__` is intended mainly to allow subclasses of immutable types " "(like int, str, or tuple) to customize instance creation. It is also " "commonly overridden in custom metaclasses in order to customize class " "creation." msgstr "" ":meth:`__new__` es destinado principalmente para permitir a subclases de " "tipos inmutables (como int, str, o tuple) personalizar la creación de " "instancias. También es comúnmente anulado en metaclases personalizadas con " "el fin de personalizar la creación de clase." #: ../Doc/reference/datamodel.rst:1413 msgid "" "Called after the instance has been created (by :meth:`__new__`), but before " "it is returned to the caller. The arguments are those passed to the class " "constructor expression. If a base class has an :meth:`__init__` method, the " "derived class's :meth:`__init__` method, if any, must explicitly call it to " "ensure proper initialization of the base class part of the instance; for " "example: ``super().__init__([args...])``." msgstr "" "Llamado después de que la instancia ha sido creada (por :meth:`__new__`), " "pero antes es retornada a quien produce la llamada. Los argumentos son " "aquellos pasados a la expresión del constructor de la clase. Si una clase " "base tiene un método :meth:`__init__`, el método :meth:`__init__` de clase " "derivada, de existir, debe llamarlo explícitamente para asegurar la " "inicialización apropiada de la clase base que es parte de la instancia; por " "ejemplo: ``super().__init__([args…])``." #: ../Doc/reference/datamodel.rst:1420 msgid "" "Because :meth:`__new__` and :meth:`__init__` work together in constructing " "objects (:meth:`__new__` to create it, and :meth:`__init__` to customize " "it), no non-``None`` value may be returned by :meth:`__init__`; doing so " "will cause a :exc:`TypeError` to be raised at runtime." msgstr "" "Debido a que :meth:`__new__` y :meth:`__init__` trabajan juntos construyendo " "objetos (:meth:`__new__` para crearlo y :meth:`__init__` para " "personalizarlo), ningún valor distinto a ``None`` puede ser retornado por :" "meth:`__init__`; hacer esto puede causar que se lance una excepción :exc:" "`TypeError` en tiempo de ejecución." #: ../Doc/reference/datamodel.rst:1433 msgid "" "Called when the instance is about to be destroyed. This is also called a " "finalizer or (improperly) a destructor. If a base class has a :meth:" "`__del__` method, the derived class's :meth:`__del__` method, if any, must " "explicitly call it to ensure proper deletion of the base class part of the " "instance." msgstr "" "Llamado cuando la instancia es a punto de ser destruida. Esto también es " "llamado finalizador o (indebidamente) destructor. Si una clase base tiene un " "método :meth:`__del__` el método :meth:`__del__` de la clase derivada, de " "existir, debe llamarlo explícitamente para asegurar la eliminación adecuada " "de la parte de la clase base de la instancia." #: ../Doc/reference/datamodel.rst:1439 msgid "" "It is possible (though not recommended!) for the :meth:`__del__` method to " "postpone destruction of the instance by creating a new reference to it. " "This is called object *resurrection*. It is implementation-dependent " "whether :meth:`__del__` is called a second time when a resurrected object is " "about to be destroyed; the current :term:`CPython` implementation only calls " "it once." msgstr "" "Es posible (¡aunque no recomendable!) para el método :meth:`__del__` " "posponer la destrucción de la instancia al crear una nueva referencia hacia " "ésta. Esto es llamado *resurrección* de objeto. Es dependiente de la " "implementación si :meth:`__del__` es llamado una segunda vez cuando un " "objeto resucitado está por ser destruido; la implementación :term:`CPython` " "actual únicamente lo llama una vez." #: ../Doc/reference/datamodel.rst:1446 msgid "" "It is not guaranteed that :meth:`__del__` methods are called for objects " "that still exist when the interpreter exits." msgstr "" "No está garantizado que los métodos :meth:`__del__` sean llamados para " "objetos que aún existen cuando el intérprete se cierra." #: ../Doc/reference/datamodel.rst:1451 msgid "" "``del x`` doesn't directly call ``x.__del__()`` --- the former decrements " "the reference count for ``x`` by one, and the latter is only called when " "``x``'s reference count reaches zero." msgstr "" "``del x`` no llama directamente ``x.__del__()`` --- el primero disminuye el " "conteo de referencia para ``x`` uno por uno, y el segundo es llamado " "únicamente cuando el conteo de referencias de ``x`` llega a cero." #: ../Doc/reference/datamodel.rst:1456 msgid "" "It is possible for a reference cycle to prevent the reference count of an " "object from going to zero. In this case, the cycle will be later detected " "and deleted by the :term:`cyclic garbage collector `. A " "common cause of reference cycles is when an exception has been caught in a " "local variable. The frame's locals then reference the exception, which " "references its own traceback, which references the locals of all frames " "caught in the traceback." msgstr "" "Es posible que un ciclo de referencia evite que el recuento de referencia de " "un objeto llegue a cero. En este caso, el ciclo será posteriormente " "detectado y eliminado por el :term:`cyclic garbage collector `. Una causa común de los ciclos de referencia es cuando se " "detecta una excepción en una variable local. Luego, los locales del marco " "hacen referencia a la excepción, que hace referencia a su propio rastreo, " "que hace referencia a los locales de todos los marcos capturados en el " "rastreo." #: ../Doc/reference/datamodel.rst:1466 msgid "Documentation for the :mod:`gc` module." msgstr "Documentación para el módulo :mod:`gc`." #: ../Doc/reference/datamodel.rst:1470 msgid "" "Due to the precarious circumstances under which :meth:`__del__` methods are " "invoked, exceptions that occur during their execution are ignored, and a " "warning is printed to ``sys.stderr`` instead. In particular:" msgstr "" "Debido a las circunstancias inciertas bajo las que los métodos :meth:" "`__del__` son invocados, las excepciones que ocurren durante su ejecución " "son ignoradas, y una advertencia es mostrada hacia ``sys.stderr``. En " "particular:" #: ../Doc/reference/datamodel.rst:1474 msgid "" ":meth:`__del__` can be invoked when arbitrary code is being executed, " "including from any arbitrary thread. If :meth:`__del__` needs to take a " "lock or invoke any other blocking resource, it may deadlock as the resource " "may already be taken by the code that gets interrupted to execute :meth:" "`__del__`." msgstr "" ":meth:`__del__` puede ser invocado cuando código arbitrario es ejecutado, " "incluyendo el de cualquier hilo arbitrario. Si :meth:`__del__` necesita " "realizar un cierre de exclusión mutua (*lock*) o invocar cualquier otro " "recurso que lo esté bloqueando, podría provocar un bloqueo muto (*deadlock*) " "ya que el recurso podría estar siendo utilizado por el código que se " "interrumpe al ejecutar :meth:`__del__`." #: ../Doc/reference/datamodel.rst:1480 msgid "" ":meth:`__del__` can be executed during interpreter shutdown. As a " "consequence, the global variables it needs to access (including other " "modules) may already have been deleted or set to ``None``. Python guarantees " "that globals whose name begins with a single underscore are deleted from " "their module before other globals are deleted; if no other references to " "such globals exist, this may help in assuring that imported modules are " "still available at the time when the :meth:`__del__` method is called." msgstr "" ":meth:`__del__` puede ser ejecutado durante el cierre del intérprete. Como " "consecuencia, las variables globales que necesita para acceder (incluyendo " "otros módulos) podrían haber sido borradas o establecidas a ``None``. Python " "garantiza que los globales cuyo nombre comienza con un guión bajo simple " "sean borrados de su módulo antes que los globales sean borrados; si no " "existen otras referencias a dichas globales, esto puede ayudar asegurando " "que los módulos importados aún se encuentren disponibles al momento de " "llamar al método :meth:`__del__`." #: ../Doc/reference/datamodel.rst:1495 msgid "" "Called by the :func:`repr` built-in function to compute the \"official\" " "string representation of an object. If at all possible, this should look " "like a valid Python expression that could be used to recreate an object with " "the same value (given an appropriate environment). If this is not possible, " "a string of the form ``<...some useful description...>`` should be returned. " "The return value must be a string object. If a class defines :meth:" "`__repr__` but not :meth:`__str__`, then :meth:`__repr__` is also used when " "an \"informal\" string representation of instances of that class is required." msgstr "" "Llamado por la función incorporada :func:`repr` para calcular la cadena " "“oficial” de representación de un objeto. Si es posible, esto debería verse " "como una expresión de Python válida que puede ser utilizada para recrear un " "objeto con el mismo valor (bajo el ambiente adecuado). Si no es posible, una " "cadena con la forma ``<…some useful description…>`` debe ser retornada. El " "valor de retorno debe ser un objeto de cadena (*string*). Si una clase " "define :meth:`__repr__` pero no :meth:`__str__`, entonces :meth:`__repr__` " "también es utilizado cuando una cadena “informal” de representación de " "instancias de esas clases son requeridas." #: ../Doc/reference/datamodel.rst:1504 msgid "" "This is typically used for debugging, so it is important that the " "representation is information-rich and unambiguous." msgstr "" "Esto es típicamente utilizado para depurar, así que es importante que la " "representación sea rica en información e inequívoca." #: ../Doc/reference/datamodel.rst:1515 msgid "" "Called by :func:`str(object) ` and the built-in functions :func:" "`format` and :func:`print` to compute the \"informal\" or nicely printable " "string representation of an object. The return value must be a :ref:`string " "` object." msgstr "" "Llamado por :func:`str(object) ` y las funciones incorporadas :func:" "`format` y :func:`print` para calcular la “informal” o bien mostrada cadena " "de representación de un objeto. El valor de retorno debe ser un objeto :ref:" "`string `." #: ../Doc/reference/datamodel.rst:1520 msgid "" "This method differs from :meth:`object.__repr__` in that there is no " "expectation that :meth:`__str__` return a valid Python expression: a more " "convenient or concise representation can be used." msgstr "" "Este método difiere de :meth:`object.__repr__` en que no hay expectativas de " "que :meth:`__str__` retorne una expresión de Python válida: una " "representación más conveniente o concisa pueda ser utilizada." #: ../Doc/reference/datamodel.rst:1524 msgid "" "The default implementation defined by the built-in type :class:`object` " "calls :meth:`object.__repr__`." msgstr "" "La implementación por defecto definida por el tipo incorporado :class:" "`object` llama a :meth:`object.__repr__`." #: ../Doc/reference/datamodel.rst:1534 msgid "" "Called by :ref:`bytes ` to compute a byte-string representation " "of an object. This should return a :class:`bytes` object." msgstr "" "Llamado por :ref:`bytes ` para calcular la representación de la " "cadena de byte de un objeto. Este deberá retornar un objeto :class:`bytes`." #: ../Doc/reference/datamodel.rst:1545 msgid "" "Called by the :func:`format` built-in function, and by extension, evaluation " "of :ref:`formatted string literals ` and the :meth:`str.format` " "method, to produce a \"formatted\" string representation of an object. The " "*format_spec* argument is a string that contains a description of the " "formatting options desired. The interpretation of the *format_spec* argument " "is up to the type implementing :meth:`__format__`, however most classes will " "either delegate formatting to one of the built-in types, or use a similar " "formatting option syntax." msgstr "" "Llamado por la función incorporada :func:`format`, y por extensión, la " "evaluación de :ref:`formatted string literals ` y el método :meth:" "`str.format`, para producir la representación “formateada” de un objeto. El " "argumento *format_spec* es una cadena que contiene una descripción de las " "opciones de formato deseadas. La interpretación del argumento *format_spec* " "depende del tipo que implementa :meth:`__format__`, sin embargo, ya sea que " "la mayoría de las clases deleguen el formato a uno de los tipos " "incorporados, o utilicen una sintaxis de opción de formato similar." #: ../Doc/reference/datamodel.rst:1555 msgid "" "See :ref:`formatspec` for a description of the standard formatting syntax." msgstr "" "Ver :ref:`formatspec` para una descripción de la sintaxis de formato " "estándar." #: ../Doc/reference/datamodel.rst:1557 msgid "The return value must be a string object." msgstr "El valor de retorno debe ser un objeto de cadena." #: ../Doc/reference/datamodel.rst:1559 msgid "" "The __format__ method of ``object`` itself raises a :exc:`TypeError` if " "passed any non-empty string." msgstr "" "El método __format__ del mismo ``object`` lanza un :exc:`TypeError` si se la " "pasa una cadena no vacía." #: ../Doc/reference/datamodel.rst:1563 msgid "" "``object.__format__(x, '')`` is now equivalent to ``str(x)`` rather than " "``format(str(x), '')``." msgstr "" "``object.__format__(x, ‘’)`` es ahora equivalente a ``str(x)`` en lugar de " "``format(str(self), ‘’)``." #: ../Doc/reference/datamodel.rst:1579 msgid "" "These are the so-called \"rich comparison\" methods. The correspondence " "between operator symbols and method names is as follows: ``xy`` calls ``x.__gt__(y)``, and ``x>=y`` " "calls ``x.__ge__(y)``." msgstr "" "Estos son los llamados métodos de comparación *rich*. La correspondencia " "entre símbolos de operador y los nombres de método es de la siguiente " "manera: ``xy`` " "llama ``x.__gt__(y)``, y ``x>=y`` llama ``x.__ge__(y)``." #: ../Doc/reference/datamodel.rst:1585 msgid "" "A rich comparison method may return the singleton ``NotImplemented`` if it " "does not implement the operation for a given pair of arguments. By " "convention, ``False`` and ``True`` are returned for a successful comparison. " "However, these methods can return any value, so if the comparison operator " "is used in a Boolean context (e.g., in the condition of an ``if`` " "statement), Python will call :func:`bool` on the value to determine if the " "result is true or false." msgstr "" "Un método de comparación *rich* puede retornar el único ``NotImplemented`` " "si no implementa la operación para un par de argumentos dados. Por " "convención, ``False`` y ``True`` son retornados para una comparación " "exitosa. Sin embargo, estos métodos pueden retornar cualquier valor, así que " "si el operador de comparación es utilizado en un contexto Booleano (p. ej. " "en la condición de una sentencia ``if``), Python llamará :func:`bool` en " "dicho valor para determinar si el resultado es verdadero (*true*) o falso " "(*false*)." #: ../Doc/reference/datamodel.rst:1592 msgid "" "By default, ``object`` implements :meth:`__eq__` by using ``is``, returning " "``NotImplemented`` in the case of a false comparison: ``True if x is y else " "NotImplemented``. For :meth:`__ne__`, by default it delegates to :meth:" "`__eq__` and inverts the result unless it is ``NotImplemented``. There are " "no other implied relationships among the comparison operators or default " "implementations; for example, the truth of ``(x.__hash__``." msgstr "" "Si una clase que anula :meth:`__eq__` necesita conservar la implementación " "de :meth:`__hash__` de una clase padre, al intérprete se le debe informar " "explícitamente estableciendo ``__hash__ = .__hash__``." #: ../Doc/reference/datamodel.rst:1668 msgid "" "If a class that does not override :meth:`__eq__` wishes to suppress hash " "support, it should include ``__hash__ = None`` in the class definition. A " "class which defines its own :meth:`__hash__` that explicitly raises a :exc:" "`TypeError` would be incorrectly identified as hashable by an " "``isinstance(obj, collections.abc.Hashable)`` call." msgstr "" "Si una clase que no anula :meth:`__eq__` desea eliminar el soporte de " "*hash*, debe incluir ``__hash__ = None`` en la definición de clase. Una " "clase que define su propio :meth:`__hash__` y que explícitamente lanza un :" "exc:`TypeError` será identificado de manera incorrecta como de hash " "calculable por una llamada ``isinstance(obj, collections.abc.Hashable)``." #: ../Doc/reference/datamodel.rst:1677 msgid "" "By default, the :meth:`__hash__` values of str and bytes objects are " "\"salted\" with an unpredictable random value. Although they remain " "constant within an individual Python process, they are not predictable " "between repeated invocations of Python." msgstr "" "Por defecto los valores de objetos str y bytes de :meth:`__hash__` son " "“salados” con un valor aleatorio impredecible. Aunque se mantienen " "constantes dentro de un proceso Python particular, no son predecibles entre " "invocaciones repetidas de Python." #: ../Doc/reference/datamodel.rst:1682 msgid "" "This is intended to provide protection against a denial-of-service caused by " "carefully chosen inputs that exploit the worst case performance of a dict " "insertion, O(n\\ :sup:`2`) complexity. See http://ocert.org/advisories/" "ocert-2011-003.html for details." msgstr "" "Esto tiene como objetivo brindar protección contra una denegación de " "servicio causada por entradas cuidadosamente elegidas que explotan el peor " "rendimiento de una inserción de dict, complejidad O(n\\ :sup:`2`). Consulte " "http://ocert.org/advisories/ocert-2011-003.html para obtener más detalles." #: ../Doc/reference/datamodel.rst:1687 msgid "" "Changing hash values affects the iteration order of sets. Python has never " "made guarantees about this ordering (and it typically varies between 32-bit " "and 64-bit builds)." msgstr "" "Cambiar los valores hash afectan el orden de la iteración de los sets. " "Python nunca ha dado garantías en relación a este orden (y típicamente varía " "entre estructuras de 32-bits y 64-bits)." #: ../Doc/reference/datamodel.rst:1691 msgid "See also :envvar:`PYTHONHASHSEED`." msgstr "Ver también :envvar:`PYTHONHASHSEED`." #: ../Doc/reference/datamodel.rst:1693 msgid "Hash randomization is enabled by default." msgstr "La aleatorización de hash es habilitada por defecto." #: ../Doc/reference/datamodel.rst:1701 msgid "" "Called to implement truth value testing and the built-in operation " "``bool()``; should return ``False`` or ``True``. When this method is not " "defined, :meth:`~object.__len__` is called, if it is defined, and the object " "is considered true if its result is nonzero. If a class defines neither :" "meth:`!__len__` nor :meth:`!__bool__`, all its instances are considered true." msgstr "" "Llamado a implementar pruebas de valor de verdad y la operación incorporada " "``bool()``; debería retornar ``False`` o ``True``. Cuando este método no " "está definido, se llama a :meth:`~object.__len__`, si está definido, y el " "objeto se considera verdadero si su resultado es distinto de cero. Si una " "clase no define ni :meth:`!__len__` ni :meth:`!__bool__`, todas sus " "instancias se consideran verdaderas." #: ../Doc/reference/datamodel.rst:1712 msgid "Customizing attribute access" msgstr "Personalizando acceso a atributos" #: ../Doc/reference/datamodel.rst:1714 msgid "" "The following methods can be defined to customize the meaning of attribute " "access (use of, assignment to, or deletion of ``x.name``) for class " "instances." msgstr "" "Los siguientes métodos pueden ser definidos para personalizar el significado " "de acceso a atributos (uso de, asignación a, o borrado de ``x.name``) para " "instancias de clase." #: ../Doc/reference/datamodel.rst:1722 msgid "" "Called when the default attribute access fails with an :exc:`AttributeError` " "(either :meth:`__getattribute__` raises an :exc:`AttributeError` because " "*name* is not an instance attribute or an attribute in the class tree for " "``self``; or :meth:`__get__` of a *name* property raises :exc:" "`AttributeError`). This method should either return the (computed) " "attribute value or raise an :exc:`AttributeError` exception." msgstr "" "Es llamado cuando el acceso a atributos por defecto falla con un :exc:" "`AttributeError` (ya sea que :meth:`__getattribute__` lanza una excepción :" "exc:`AttributeError` porque *name* no es un atributo de instancia o un " "atributo en el árbol de clase para ``self``; o el :meth:`__get__` de la " "propiedad de *name* lanza una excepción :exc:`AttributeError`). Este método " "debe retornar el valor de atributo (calculado) o lanzar una excepción :exc:" "`AttributeError`." #: ../Doc/reference/datamodel.rst:1729 msgid "" "Note that if the attribute is found through the normal mechanism, :meth:" "`__getattr__` is not called. (This is an intentional asymmetry between :" "meth:`__getattr__` and :meth:`__setattr__`.) This is done both for " "efficiency reasons and because otherwise :meth:`__getattr__` would have no " "way to access other attributes of the instance. Note that at least for " "instance variables, you can fake total control by not inserting any values " "in the instance attribute dictionary (but instead inserting them in another " "object). See the :meth:`__getattribute__` method below for a way to " "actually get total control over attribute access." msgstr "" "Tome en cuenta que si el atributo es encontrado a través del mecanismo " "normal, :meth:`__getattr__` no es llamado. (Esto es una desigualdad " "intencional entre :meth:`__getattr__` y :meth:`__setattr__`.) Esto es " "realizado tanto por motivos de eficiencia y porque de otra manera :meth:" "`__getattr__` no tendría manera de acceder a otros atributos de la " "instancia. Tome en cuenta que al menos para variables de instancia, se puede " "fingir control total al no insertar ningún valor en el diccionario de " "atributo de instancia (sino insertándolos en otro objeto). Ver el método :" "meth:`__getattribute__` a continuación para una forma de tener control total " "sobre el acceso de atributo." #: ../Doc/reference/datamodel.rst:1742 msgid "" "Called unconditionally to implement attribute accesses for instances of the " "class. If the class also defines :meth:`__getattr__`, the latter will not be " "called unless :meth:`__getattribute__` either calls it explicitly or raises " "an :exc:`AttributeError`. This method should return the (computed) attribute " "value or raise an :exc:`AttributeError` exception. In order to avoid " "infinite recursion in this method, its implementation should always call the " "base class method with the same name to access any attributes it needs, for " "example, ``object.__getattribute__(self, name)``." msgstr "" "Es llamado incondicionalmente para implementar acceso de atributo por " "instancias de clase. Si la clase también define :meth:`__getattr__`, éste no " "será llamado a menos que :meth:`__getattribute__` lo llame de manera " "explícita o lance una excepción :exc:`AttributeError`. Este método deberá " "retornar el valor de atributo (calculado) o lanzar una excepción :exc:" "`AttributeError`. Para evitar la recursividad infinita en este método, su " "implementación deberá siempre llamar al método de la clase base con el mismo " "nombre para acceder cualquier atributo que necesite, por ejemplo, ``object." "__getattribute__(self, name)``." #: ../Doc/reference/datamodel.rst:1753 msgid "" "This method may still be bypassed when looking up special methods as the " "result of implicit invocation via language syntax or built-in functions. " "See :ref:`special-lookup`." msgstr "" "Este método aún puede ser sobrepasado cuando se buscan métodos especiales " "como resultado de una invocación implícita a través de sintaxis de lenguaje " "o funciones implícitas. Ver :ref:`special-lookup`." #: ../Doc/reference/datamodel.rst:1757 msgid "" "Raises an :ref:`auditing event ` ``object.__getattr__`` with " "arguments ``obj``, ``name``." msgstr "" "Lanza un :ref:`evento de auditoría ` ``object.__getattr__`` con " "argumentos ``obj``, ``name``." #: ../Doc/reference/datamodel.rst:1759 msgid "" "For certain sensitive attribute accesses, raises an :ref:`auditing event " "` ``object.__getattr__`` with arguments ``obj`` and ``name``." msgstr "" "Para ciertos accesos a atributos sensibles, lanza un :ref:`evento de " "auditoría ` ``object.__getattr__`` con los argumentos ``obj`` y " "``name``." #: ../Doc/reference/datamodel.rst:1766 msgid "" "Called when an attribute assignment is attempted. This is called instead of " "the normal mechanism (i.e. store the value in the instance dictionary). " "*name* is the attribute name, *value* is the value to be assigned to it." msgstr "" "Es llamado cuando se intenta la asignación de atributos. Éste es llamado en " "lugar del mecanismo normal (p. ej. guardar el valor en el diccionario de " "instancias). *name* es el nombre de atributo, *value* es el valor que se le " "asigna." #: ../Doc/reference/datamodel.rst:1770 msgid "" "If :meth:`__setattr__` wants to assign to an instance attribute, it should " "call the base class method with the same name, for example, ``object." "__setattr__(self, name, value)``." msgstr "" "Si :meth:`__setattr__` quiere asignar a un atributo de instancia, debe " "llamar al método de la clase base con el mismo nombre, por ejemplo, ``object." "__setattr__(self, name, value)``." #: ../Doc/reference/datamodel.rst:1774 msgid "" "Raises an :ref:`auditing event ` ``object.__setattr__`` with " "arguments ``obj``, ``name``, ``value``." msgstr "" "Lanza un :ref:`evento de auditoría ` ``object.__setattr__`` con " "argumentos ``obj``, ``name``, ``value``." #: ../Doc/reference/datamodel.rst:1776 msgid "" "For certain sensitive attribute assignments, raises an :ref:`auditing event " "` ``object.__setattr__`` with arguments ``obj``, ``name``, " "``value``." msgstr "" "Para ciertas asignaciones de atributos sensibles, lanza un :ref:`evento de " "auditoría ` ``object.__setattr__`` con argumentos ``obj``, " "``name``, ``value``." #: ../Doc/reference/datamodel.rst:1783 msgid "" "Like :meth:`__setattr__` but for attribute deletion instead of assignment. " "This should only be implemented if ``del obj.name`` is meaningful for the " "object." msgstr "" "Al igual que :meth:`__setattr__` pero para borrado de atributos en lugar de " "establecerlos. Esto solo de ser implementado si ``del obj.name`` es " "significativo para el objeto." #: ../Doc/reference/datamodel.rst:1786 msgid "" "Raises an :ref:`auditing event ` ``object.__delattr__`` with " "arguments ``obj``, ``name``." msgstr "" "Lanza un :ref:`evento de auditoría ` ``object.__delattr__`` con " "argumentos ``obj``, ``name``." #: ../Doc/reference/datamodel.rst:1788 msgid "" "For certain sensitive attribute deletions, raises an :ref:`auditing event " "` ``object.__delattr__`` with arguments ``obj`` and ``name``." msgstr "" "Para ciertas eliminaciones de atributos sensibles, lanza un :ref:`evento de " "auditoría ` ``object.__delattr__`` con argumentos ``obj`` y " "``name``." #: ../Doc/reference/datamodel.rst:1795 msgid "" "Called when :func:`dir` is called on the object. A sequence must be " "returned. :func:`dir` converts the returned sequence to a list and sorts it." msgstr "" "Es llamado cuando :func:`dir` es llamado en el objeto. Una secuencia debe " "ser retornada. :func:`dir` convierte la secuencia retornada a una lista y la " "ordena." #: ../Doc/reference/datamodel.rst:1800 msgid "Customizing module attribute access" msgstr "Personalizando acceso a atributos de módulo" #: ../Doc/reference/datamodel.rst:1807 msgid "" "Special names ``__getattr__`` and ``__dir__`` can be also used to customize " "access to module attributes. The ``__getattr__`` function at the module " "level should accept one argument which is the name of an attribute and " "return the computed value or raise an :exc:`AttributeError`. If an attribute " "is not found on a module object through the normal lookup, i.e. :meth:" "`object.__getattribute__`, then ``__getattr__`` is searched in the module " "``__dict__`` before raising an :exc:`AttributeError`. If found, it is called " "with the attribute name and the result is returned." msgstr "" "Nombres especiales ``__getattr__`` y ``__dir__`` también pueden ser " "utilizados para personalizar acceso a atributos de módulo. La función " "``__getattr__`` a nivel del módulo debe aceptar un argumento que es el " "nombre del atributo y retornar el valor calculado o lanzar una excepción :" "exc:`AttributeError`. Si un atributo no es encontrado en el objeto de módulo " "a través de una búsqueda normal, p. ej. :meth:`object.__getattribute__`, " "entonces ``__getattr__`` es buscado en el módulo ``__dict__`` antes de " "lanzar una excepción :exc:`AttributeError`. Si es encontrado, es llamado con " "el nombre de atributo y el resultado es retornado." #: ../Doc/reference/datamodel.rst:1816 msgid "" "The ``__dir__`` function should accept no arguments, and return a sequence " "of strings that represents the names accessible on module. If present, this " "function overrides the standard :func:`dir` search on a module." msgstr "" "La función ``__dir__`` debe no aceptar argumentos y retornar una secuencia " "de cadena de caracteres que representan los nombres accesibles en el módulo. " "De existir, esta función anula la búsqueda estándar :func:`dir` en un módulo." #: ../Doc/reference/datamodel.rst:1820 msgid "" "For a more fine grained customization of the module behavior (setting " "attributes, properties, etc.), one can set the ``__class__`` attribute of a " "module object to a subclass of :class:`types.ModuleType`. For example::" msgstr "" "Para una personalización más precisa sobre el comportamiento del módulo " "(estableciendo atributos, propiedades, etc.), se puede establecer el " "atributo ``__class__`` de un objeto de módulo a una subclase de :class:" "`types.ModuleType`. Por ejemplo::" #: ../Doc/reference/datamodel.rst:1838 msgid "" "Defining module ``__getattr__`` and setting module ``__class__`` only affect " "lookups made using the attribute access syntax -- directly accessing the " "module globals (whether by code within the module, or via a reference to the " "module's globals dictionary) is unaffected." msgstr "" "Definiendo un módulo ``__getattr__`` y estableciendo un módulo ``__class__`` " "solo afecta búsquedas que utilizan la sintaxis de acceso a atributo -- " "acceder directamente a las globales del módulo (ya sea por código dentro del " "módulo, o a través de una referencia al diccionario de globales del módulo) " "no se ve afectado." #: ../Doc/reference/datamodel.rst:1843 msgid "``__class__`` module attribute is now writable." msgstr "El atributo de módulo ``__class__`` es ahora escribible." #: ../Doc/reference/datamodel.rst:1846 msgid "``__getattr__`` and ``__dir__`` module attributes." msgstr "Atributos de módulo ``__getattr__`` y ``__dir__``." #: ../Doc/reference/datamodel.rst:1851 msgid ":pep:`562` - Module __getattr__ and __dir__" msgstr ":pep:`562` - Módulos __getattr__ y __dir__" #: ../Doc/reference/datamodel.rst:1852 msgid "Describes the ``__getattr__`` and ``__dir__`` functions on modules." msgstr "Describe las funciones ``__getattr__`` y ``__dir__`` en módulos." #: ../Doc/reference/datamodel.rst:1858 msgid "Implementing Descriptors" msgstr "Implementando descriptores" #: ../Doc/reference/datamodel.rst:1860 msgid "" "The following methods only apply when an instance of the class containing " "the method (a so-called *descriptor* class) appears in an *owner* class (the " "descriptor must be in either the owner's class dictionary or in the class " "dictionary for one of its parents). In the examples below, \"the " "attribute\" refers to the attribute whose name is the key of the property in " "the owner class' :attr:`~object.__dict__`." msgstr "" "Los siguientes métodos solo aplican cuando una instancia de clase que " "contiene el método (llamado clase *descriptora*) aparece en una clase " "*propietaria* (el descriptor debe estar en el diccionario de clase del " "propietario o en el diccionario de clase de alguno de sus padres). En los " "ejemplos a continuación, “el atributo” se refiere al atributo cuyo nombre es " "la llave de la propiedad en la clase propietaria :attr:`~object.__dict__`." #: ../Doc/reference/datamodel.rst:1870 msgid "" "Called to get the attribute of the owner class (class attribute access) or " "of an instance of that class (instance attribute access). The optional " "*owner* argument is the owner class, while *instance* is the instance that " "the attribute was accessed through, or ``None`` when the attribute is " "accessed through the *owner*." msgstr "" "Es llamado para obtener el atributo de la clase propietaria (acceso a " "atributos de clase) o de una instancia de dicha clase (acceso a atributos de " "instancia). El argumento opcional *owner* es la clase propietaria, mientras " "que *instance* es la instancia a través de la cual el atributo fue accedido, " "o ``None`` cuando el atributo es accedido a través de *owner*." #: ../Doc/reference/datamodel.rst:1876 msgid "" "This method should return the computed attribute value or raise an :exc:" "`AttributeError` exception." msgstr "" "Este método debe retornar el valor de atributo calculado o lanzar una " "excepción :exc:`AttributeError`." #: ../Doc/reference/datamodel.rst:1879 msgid "" ":PEP:`252` specifies that :meth:`__get__` is callable with one or two " "arguments. Python's own built-in descriptors support this specification; " "however, it is likely that some third-party tools have descriptors that " "require both arguments. Python's own :meth:`__getattribute__` " "implementation always passes in both arguments whether they are required or " "not." msgstr "" ":PEP:`252` especifica que :meth:`__get__` puede ser llamado con uno o dos " "argumentos. Los propios descriptores incorporados de Python soportan esta " "especificación; sin embargo, es probable que algunas herramientas de " "terceros tengan descriptores que requieran ambos argumentos. La propia " "implementación de :meth:`__getattribute__` en Python siempre pasa ambos " "argumentos si son requeridos o no." #: ../Doc/reference/datamodel.rst:1888 msgid "" "Called to set the attribute on an instance *instance* of the owner class to " "a new value, *value*." msgstr "" "Es llamado para establecer el atributo en una instancia *instance* de la " "clase propietaria a un nuevo valor *value*." #: ../Doc/reference/datamodel.rst:1891 msgid "" "Note, adding :meth:`__set__` or :meth:`__delete__` changes the kind of " "descriptor to a \"data descriptor\". See :ref:`descriptor-invocation` for " "more details." msgstr "" "Nota, agregar :meth:`__set__` o :meth:`__delete__` cambia el tipo de " "descriptor a un “descriptor de datos”. Ver :ref:`descriptor-invocation` para " "más detalles." #: ../Doc/reference/datamodel.rst:1897 msgid "" "Called to delete the attribute on an instance *instance* of the owner class." msgstr "" "Es llamado para borrar el atributo en una instancia *instance* de la clase " "propietaria." #: ../Doc/reference/datamodel.rst:1900 msgid "" "The attribute :attr:`__objclass__` is interpreted by the :mod:`inspect` " "module as specifying the class where this object was defined (setting this " "appropriately can assist in runtime introspection of dynamic class " "attributes). For callables, it may indicate that an instance of the given " "type (or a subclass) is expected or required as the first positional " "argument (for example, CPython sets this attribute for unbound methods that " "are implemented in C)." msgstr "" "El atributo :attr:`__objclass__` es interpretado por el módulo :mod:" "`inspect` como la especificación de la clase donde el objeto fue definido " "(establecer esto adecuadamente puede ayudar en introspección de atributos " "dinámicos de clases en tiempo de ejecución). Para invocables, puede indicar " "que una instancia de un tipo (o subclase) dado es esperado o requerido como " "el primero argumento posicional (por ejemplo, CPython establece este " "atributo para métodos independientes que son implementados en C)." #: ../Doc/reference/datamodel.rst:1911 msgid "Invoking Descriptors" msgstr "Invocando descriptores" #: ../Doc/reference/datamodel.rst:1913 msgid "" "In general, a descriptor is an object attribute with \"binding behavior\", " "one whose attribute access has been overridden by methods in the descriptor " "protocol: :meth:`~object.__get__`, :meth:`~object.__set__`, and :meth:" "`~object.__delete__`. If any of those methods are defined for an object, it " "is said to be a descriptor." msgstr "" "En general, un descriptor es un atributo de objeto con \"comportamiento " "vinculante\", uno cuyo acceso al atributo ha sido anulado por métodos en el " "protocolo del descriptor: :meth:`~object.__get__`, :meth:`~object.__set__` " "y :meth:`~object.__delete__`. Si alguno de esos métodos está definido para " "un objeto, se dice que es un descriptor." #: ../Doc/reference/datamodel.rst:1919 msgid "" "The default behavior for attribute access is to get, set, or delete the " "attribute from an object's dictionary. For instance, ``a.x`` has a lookup " "chain starting with ``a.__dict__['x']``, then ``type(a).__dict__['x']``, and " "continuing through the base classes of ``type(a)`` excluding metaclasses." msgstr "" "El comportamiento por defecto para atributos de acceso es obtener (*get*), " "establecer (*set*) o borrar (*delete*) el atributo del diccionario del " "objeto. Por ejemplo, ``a.x`` tiene una cadena de búsqueda que comienza con " "``a.__dict__[‘x’]``, luego ``type(a).__dict__[‘x’]``, y continúa por las " "clases base de ``type(a)`` excluyendo metaclases." #: ../Doc/reference/datamodel.rst:1924 msgid "" "However, if the looked-up value is an object defining one of the descriptor " "methods, then Python may override the default behavior and invoke the " "descriptor method instead. Where this occurs in the precedence chain " "depends on which descriptor methods were defined and how they were called." msgstr "" "Sin embargo, si el valor buscado es un objeto definiendo uno de los métodos " "del descriptor, entonces Python puede anular el comportamiento por defecto e " "invocar al método del descriptor en su lugar. Dónde ocurre esto en la cadena " "de precedencia depende de qué métodos de descriptor fueron definidos y cómo " "son llamados." #: ../Doc/reference/datamodel.rst:1929 msgid "" "The starting point for descriptor invocation is a binding, ``a.x``. How the " "arguments are assembled depends on ``a``:" msgstr "" "El punto de inicio por invocación de descriptor es un enlace ``a.x``. Cómo " "los argumentos son ensamblados dependen de ``a``:" #: ../Doc/reference/datamodel.rst:1934 msgid "Direct Call" msgstr "Llamado directo" #: ../Doc/reference/datamodel.rst:1933 msgid "" "The simplest and least common call is when user code directly invokes a " "descriptor method: ``x.__get__(a)``." msgstr "" "El llamado más simple y menos común es cuando el código de usuario invoca " "directamente un método descriptor: ``x.__get__(a)``." #: ../Doc/reference/datamodel.rst:1938 msgid "Instance Binding" msgstr "Enlace de instancia" #: ../Doc/reference/datamodel.rst:1937 msgid "" "If binding to an object instance, ``a.x`` is transformed into the call: " "``type(a).__dict__['x'].__get__(a, type(a))``." msgstr "" "Al enlazar a una instancia de objeto, ``a`` es transformado en un llamado: " "``type(a).__dict__[‘x’].__get__(a, type(a))``." #: ../Doc/reference/datamodel.rst:1942 msgid "Class Binding" msgstr "Enlace de clase" #: ../Doc/reference/datamodel.rst:1941 msgid "" "If binding to a class, ``A.x`` is transformed into the call: ``A." "__dict__['x'].__get__(None, A)``." msgstr "" "Al enlazar a una clase, ``A.x`` es transformado en un llamado: ``A." "__dict__[‘x’].__get__(None, A)``." #: ../Doc/reference/datamodel.rst:1948 msgid "Super Binding" msgstr "Súper enlace" #: ../Doc/reference/datamodel.rst:1945 msgid "" "A dotted lookup such as ``super(A, a).x`` searches ``a.__class__.__mro__`` " "for a base class ``B`` following ``A`` and then returns ``B.__dict__['x']." "__get__(a, A)``. If not a descriptor, ``x`` is returned unchanged." msgstr "" "Una búsqueda punteada como ``super(A, a).x`` busca en ``a.__class__." "__mro__`` una clase base ``B`` después de ``A`` y luego retorna ``B." "__dict__['x'].__get__(a, A)``. Si no es un descriptor, ``x`` se retorna sin " "cambios." #: ../Doc/reference/datamodel.rst:1982 msgid "" "For instance bindings, the precedence of descriptor invocation depends on " "which descriptor methods are defined. A descriptor can define any " "combination of :meth:`~object.__get__`, :meth:`~object.__set__` and :meth:" "`~object.__delete__`. If it does not define :meth:`__get__`, then accessing " "the attribute will return the descriptor object itself unless there is a " "value in the object's instance dictionary. If the descriptor defines :meth:" "`__set__` and/or :meth:`__delete__`, it is a data descriptor; if it defines " "neither, it is a non-data descriptor. Normally, data descriptors define " "both :meth:`__get__` and :meth:`__set__`, while non-data descriptors have " "just the :meth:`__get__` method. Data descriptors with :meth:`__get__` and :" "meth:`__set__` (and/or :meth:`__delete__`) defined always override a " "redefinition in an instance dictionary. In contrast, non-data descriptors " "can be overridden by instances." msgstr "" "Por ejemplo, enlaces, la precedencia de la invocación de descriptores " "depende de qué métodos de descriptores están definidos. Un descriptor puede " "definir cualquier combinación de :meth:`~object.__get__`, :meth:`~object." "__set__` y :meth:`~object.__delete__`. Si no define :meth:`__get__`, acceder " "al atributo retornará el objeto descriptor en sí, a menos que haya un valor " "en el diccionario de instancia del objeto. Si el descriptor define :meth:" "`__set__` y/o :meth:`__delete__`, es un descriptor de datos; si no define " "ninguno de los dos, es un descriptor que no es de datos. Normalmente, los " "descriptores de datos definen tanto :meth:`__get__` como :meth:`__set__`, " "mientras que los descriptores que no son de datos tienen solo el método :" "meth:`__get__`. Los descriptores de datos con :meth:`__get__` y :meth:" "`__set__` (y/o :meth:`__delete__`) definidos siempre anulan una redefinición " "en un diccionario de instancia. Por el contrario, las instancias pueden " "anular los descriptores que no son datos." #: ../Doc/reference/datamodel.rst:1996 msgid "" "Python methods (including those decorated with :func:`@staticmethod " "` and :func:`@classmethod `) are implemented as " "non-data descriptors. Accordingly, instances can redefine and override " "methods. This allows individual instances to acquire behaviors that differ " "from other instances of the same class." msgstr "" "Los métodos de Python (incluidos los decorados con :func:`@staticmethod " "` y :func:`@classmethod `) se implementan como " "descriptores sin datos. En consecuencia, las instancias pueden redefinir y " "anular métodos. Esto permite que las instancias individuales adquieran " "comportamientos que difieren de otras instancias de la misma clase." #: ../Doc/reference/datamodel.rst:2002 msgid "" "The :func:`property` function is implemented as a data descriptor. " "Accordingly, instances cannot override the behavior of a property." msgstr "" "La función :func:`property` es implementada como un descriptor de datos. Por " "lo tanto, las instancias no pueden anular el comportamiento de una propiedad." #: ../Doc/reference/datamodel.rst:2009 msgid "__slots__" msgstr "__slots__" #: ../Doc/reference/datamodel.rst:2011 msgid "" "*__slots__* allow us to explicitly declare data members (like properties) " "and deny the creation of :attr:`~object.__dict__` and *__weakref__* (unless " "explicitly declared in *__slots__* or available in a parent.)" msgstr "" "*__slots__* nos permite declarar explícitamente miembros de datos (como " "propiedades) y denegar la creación de :attr:`~object.__dict__` y " "*__weakref__* (a menos que se declare explícitamente en *__slots__* o esté " "disponible en un padre)." #: ../Doc/reference/datamodel.rst:2015 msgid "" "The space saved over using :attr:`~object.__dict__` can be significant. " "Attribute lookup speed can be significantly improved as well." msgstr "" "El espacio ahorrado al usar :attr:`~object.__dict__` puede ser " "significativo. La velocidad de búsqueda de atributos también se puede " "mejorar significativamente." #: ../Doc/reference/datamodel.rst:2020 msgid "" "This class variable can be assigned a string, iterable, or sequence of " "strings with variable names used by instances. *__slots__* reserves space " "for the declared variables and prevents the automatic creation of :attr:" "`~object.__dict__` and *__weakref__* for each instance." msgstr "" "A esta variable de clase se le puede asignar una cadena, un iterable o una " "secuencia de cadenas con nombres de variables utilizados por las instancias. " "*__slots__* reserva espacio para las variables declaradas y evita la " "creación automática de :attr:`~object.__dict__` y *__weakref__* para cada " "instancia." #: ../Doc/reference/datamodel.rst:2029 msgid "Notes on using *__slots__*:" msgstr "Notas sobre el uso de *__slots__*" #: ../Doc/reference/datamodel.rst:2031 msgid "" "When inheriting from a class without *__slots__*, the :attr:`~object." "__dict__` and *__weakref__* attribute of the instances will always be " "accessible." msgstr "" "Al heredar de una clase sin *__slots__*, los atributos :attr:`~object." "__dict__` y *__weakref__* de las instancias siempre estarán accesibles." #: ../Doc/reference/datamodel.rst:2035 msgid "" "Without a :attr:`~object.__dict__` variable, instances cannot be assigned " "new variables not listed in the *__slots__* definition. Attempts to assign " "to an unlisted variable name raises :exc:`AttributeError`. If dynamic " "assignment of new variables is desired, then add ``'__dict__'`` to the " "sequence of strings in the *__slots__* declaration." msgstr "" "Sin una variable :attr:`~object.__dict__`, a las instancias no se les pueden " "asignar nuevas variables que no figuran en la definición *__slots__*. Los " "intentos de asignar un nombre de variable no listado generan :exc:" "`AttributeError`. Si desea una asignación dinámica de nuevas variables, " "agregue ``'__dict__'`` a la secuencia de cadenas en la declaración " "*__slots__*." #: ../Doc/reference/datamodel.rst:2042 msgid "" "Without a *__weakref__* variable for each instance, classes defining " "*__slots__* do not support :mod:`weak references ` to its " "instances. If weak reference support is needed, then add ``'__weakref__'`` " "to the sequence of strings in the *__slots__* declaration." msgstr "" "Sin una variable *__weakref__* para cada instancia, las clases que definen " "*__slots__* no admiten :mod:`weak references ` en sus instancias. " "Si se necesita soporte de referencia débil, agregue ``'__weakref__'`` a la " "secuencia de cadenas en la declaración *__slots__*." #: ../Doc/reference/datamodel.rst:2048 msgid "" "*__slots__* are implemented at the class level by creating :ref:`descriptors " "` for each variable name. As a result, class attributes cannot " "be used to set default values for instance variables defined by *__slots__*; " "otherwise, the class attribute would overwrite the descriptor assignment." msgstr "" "*__slots__* se implementa a nivel de clase creando :ref:`descriptors " "` para cada nombre de variable. Como resultado, los atributos " "de clase no se pueden utilizar para establecer valores predeterminados, por " "ejemplo, variables definidas por *__slots__*; de lo contrario, el atributo " "de clase sobrescribiría la asignación del descriptor." #: ../Doc/reference/datamodel.rst:2054 msgid "" "The action of a *__slots__* declaration is not limited to the class where it " "is defined. *__slots__* declared in parents are available in child classes. " "However, child subclasses will get a :attr:`~object.__dict__` and " "*__weakref__* unless they also define *__slots__* (which should only contain " "names of any *additional* slots)." msgstr "" "La acción de una declaración *__slots__* no se limita a la clase donde se " "define. *__slots__* declarado en padres está disponible en clases " "secundarias. Sin embargo, las subclases secundarias obtendrán :attr:`~object." "__dict__` y *__weakref__* a menos que también definan *__slots__* (que solo " "debe contener nombres de cualquier ranura *additional*)." #: ../Doc/reference/datamodel.rst:2060 msgid "" "If a class defines a slot also defined in a base class, the instance " "variable defined by the base class slot is inaccessible (except by " "retrieving its descriptor directly from the base class). This renders the " "meaning of the program undefined. In the future, a check may be added to " "prevent this." msgstr "" "Si una clase define un espacio (*slot*) también definido en una clase base, " "la variable de instancia definida por el espacio de la clase base es " "inaccesible (excepto al obtener su descriptor directamente de la clase " "base). Esto hace que el significado del programa sea indefinido. En el " "futuro se podría agregar una verificación para prevenir esto." #: ../Doc/reference/datamodel.rst:2065 msgid "" ":exc:`TypeError` will be raised if nonempty *__slots__* are defined for a " "class derived from a :c:member:`\"variable-length\" built-in type " "` such as :class:`int`, :class:`bytes`, and :class:" "`tuple`." msgstr "" ":exc:`TypeError` se generará si se definen *__slots__* no vacíos para una " "clase derivada de un :c:member:`\"variable-length\" built-in type " "` como :class:`int`, :class:`bytes` y :class:" "`tuple`." #: ../Doc/reference/datamodel.rst:2070 msgid "Any non-string :term:`iterable` may be assigned to *__slots__*." msgstr "" "Cualquier :term:`iterable` que no sea una cadena se puede asignar a " "*__slots__*." #: ../Doc/reference/datamodel.rst:2072 msgid "" "If a :class:`dictionary ` is used to assign *__slots__*, the " "dictionary keys will be used as the slot names. The values of the dictionary " "can be used to provide per-attribute docstrings that will be recognised by :" "func:`inspect.getdoc` and displayed in the output of :func:`help`." msgstr "" "Si se utiliza un :class:`dictionary ` para asignar *__slots__*, las " "claves del diccionario se utilizarán como nombres de ranura. Los valores del " "diccionario se pueden usar para proporcionar cadenas de documentos por " "atributo que :func:`inspect.getdoc` reconocerá y mostrará en la salida de :" "func:`help`." #: ../Doc/reference/datamodel.rst:2077 msgid "" ":attr:`~instance.__class__` assignment works only if both classes have the " "same *__slots__*." msgstr "" "La asignación de :attr:`~instance.__class__` solo funciona si ambas clases " "tienen el mismo *__slots__*." #: ../Doc/reference/datamodel.rst:2080 msgid "" ":ref:`Multiple inheritance ` with multiple slotted parent " "classes can be used, but only one parent is allowed to have attributes " "created by slots (the other bases must have empty slot layouts) - violations " "raise :exc:`TypeError`." msgstr "" "Se puede usar :ref:`Multiple inheritance ` con varias clases " "principales con ranuras, pero solo a una de las clases principales se le " "permite tener atributos creados por ranuras (las otras bases deben tener " "diseños de ranuras vacías); las infracciones generan :exc:`TypeError`." #: ../Doc/reference/datamodel.rst:2086 msgid "" "If an :term:`iterator` is used for *__slots__* then a :term:`descriptor` is " "created for each of the iterator's values. However, the *__slots__* " "attribute will be an empty iterator." msgstr "" "Si se utiliza un :term:`iterator` para *__slots__*, entonces se crea un :" "term:`descriptor` para cada uno de los valores del iterador. Sin embargo, el " "atributo *__slots__* será un iterador vacío." #: ../Doc/reference/datamodel.rst:2094 msgid "Customizing class creation" msgstr "Personalización de creación de clases" #: ../Doc/reference/datamodel.rst:2096 msgid "" "Whenever a class inherits from another class, :meth:`~object." "__init_subclass__` is called on the parent class. This way, it is possible " "to write classes which change the behavior of subclasses. This is closely " "related to class decorators, but where class decorators only affect the " "specific class they're applied to, ``__init_subclass__`` solely applies to " "future subclasses of the class defining the method." msgstr "" "Siempre que una clase hereda de otra clase, se llama a :meth:`~object." "__init_subclass__` en la clase principal. De esta forma, es posible escribir " "clases que cambien el comportamiento de las subclases. Esto está " "estrechamente relacionado con los decoradores de clases, pero mientras los " "decoradores de clases solo afectan la clase específica a la que se aplican, " "``__init_subclass__`` solo se aplica a futuras subclases de la clase que " "define el método." #: ../Doc/reference/datamodel.rst:2105 msgid "" "This method is called whenever the containing class is subclassed. *cls* is " "then the new subclass. If defined as a normal instance method, this method " "is implicitly converted to a class method." msgstr "" "Este método es llamado siempre que la clase que lo contiene sea heredada. " "*cls* es entonces, la nueva subclase. Si se define como un método de " "instancia normal, éste es convertido de manera implícita a un método de " "clase." #: ../Doc/reference/datamodel.rst:2109 msgid "" "Keyword arguments which are given to a new class are passed to the parent's " "class ``__init_subclass__``. For compatibility with other classes using " "``__init_subclass__``, one should take out the needed keyword arguments and " "pass the others over to the base class, as in::" msgstr "" "Los argumentos de palabra clave que fueron dados a una nueva clase, son " "pasados a la clase ``__init_subclass__`` del padre. Por temas de " "compatibilidad con otras clases que usan ``__init_subclass__``, uno debería " "quitar los argumentos de palabra clave y pasar los otros a la clase base, " "como en::" #: ../Doc/reference/datamodel.rst:2123 msgid "" "The default implementation ``object.__init_subclass__`` does nothing, but " "raises an error if it is called with any arguments." msgstr "" "La implementación por defecto ``object.__init_subclass__`` no hace nada, " "pero lanza un error si es llamado con cualquier argumento." #: ../Doc/reference/datamodel.rst:2128 msgid "" "The metaclass hint ``metaclass`` is consumed by the rest of the type " "machinery, and is never passed to ``__init_subclass__`` implementations. The " "actual metaclass (rather than the explicit hint) can be accessed as " "``type(cls)``." msgstr "" "La sugerencia de metaclase ``metaclass`` es consumido por el resto de la " "maquinaria de tipos, y nunca se pasa a las implementaciones " "``__init_subclass__``. La clase meta actual (más que la sugerencia " "explícita) puede ser accedida como ``type(cls)``." #: ../Doc/reference/datamodel.rst:2136 msgid "" "When a class is created, :meth:`type.__new__` scans the class variables and " "makes callbacks to those with a :meth:`~object.__set_name__` hook." msgstr "" "Cuando se crea una clase, :meth:`type.__new__` escanea las variables de " "clase y realiza la retrollamada a aquellas con un enlace :meth:`~object." "__set_name__`." #: ../Doc/reference/datamodel.rst:2141 msgid "" "Automatically called at the time the owning class *owner* is created. The " "object has been assigned to *name* in that class::" msgstr "" "Llamado automáticamente al momento en el que se crea la clase propietaria " "*owner*. El objeto es asignado a *name* en esa clase::" #: ../Doc/reference/datamodel.rst:2147 msgid "" "If the class variable is assigned after the class is created, :meth:" "`__set_name__` will not be called automatically. If needed, :meth:" "`__set_name__` can be called directly::" msgstr "" "Si la variable de clase se asigna después de crear la clase, :meth:" "`__set_name__` no se llamará automáticamente. Si es necesario, :meth:" "`__set_name__` se puede llamar directamente::" #: ../Doc/reference/datamodel.rst:2158 msgid "See :ref:`class-object-creation` for more details." msgstr "Ver :ref:`class-object-creation` para más detalles." #: ../Doc/reference/datamodel.rst:2166 msgid "Metaclasses" msgstr "Metaclases" #: ../Doc/reference/datamodel.rst:2173 msgid "" "By default, classes are constructed using :func:`type`. The class body is " "executed in a new namespace and the class name is bound locally to the " "result of ``type(name, bases, namespace)``." msgstr "" "Por defecto, las clases son construidas usando :func:`type`. El cuerpo de la " "clase es ejecutado en un nuevo espacio de nombres y el nombre de la clase es " "ligado de forma local al resultado de ``type(name, bases, namespace)``." #: ../Doc/reference/datamodel.rst:2177 msgid "" "The class creation process can be customized by passing the ``metaclass`` " "keyword argument in the class definition line, or by inheriting from an " "existing class that included such an argument. In the following example, " "both ``MyClass`` and ``MySubclass`` are instances of ``Meta``::" msgstr "" "El proceso de creación de clase puede ser personalizado pasando el argumento " "de palabra clave ``metaclass`` en la línea de definición de la clase, o al " "heredar de una clase existente que incluya dicho argumento. En el siguiente " "ejemplo, ambos ``MyClass`` y ``MySubclass`` son instancias de ``Meta``::" #: ../Doc/reference/datamodel.rst:2191 msgid "" "Any other keyword arguments that are specified in the class definition are " "passed through to all metaclass operations described below." msgstr "" "Cualquier otro argumento de palabra clave que sea especificado en la " "definición de clase es pasado mediante todas las operaciones de metaclase " "descritas a continuación." #: ../Doc/reference/datamodel.rst:2194 msgid "When a class definition is executed, the following steps occur:" msgstr "" "Cuando una definición de clase es ejecutada, los siguientes pasos ocurren:" #: ../Doc/reference/datamodel.rst:2196 msgid "MRO entries are resolved;" msgstr "Entradas de la orden de resolución de método (MRU) son resueltas;" #: ../Doc/reference/datamodel.rst:2197 msgid "the appropriate metaclass is determined;" msgstr "se determina la metaclase adecuada;" #: ../Doc/reference/datamodel.rst:2198 msgid "the class namespace is prepared;" msgstr "se prepara el espacio de nombres de clase;" #: ../Doc/reference/datamodel.rst:2199 msgid "the class body is executed;" msgstr "se ejecuta el cuerpo de la clase;" #: ../Doc/reference/datamodel.rst:2200 msgid "the class object is created." msgstr "se crea el objeto de clase." #: ../Doc/reference/datamodel.rst:2204 msgid "Resolving MRO entries" msgstr "Resolviendo entradas de la Orden de Resolución de Métodos (MRU)" #: ../Doc/reference/datamodel.rst:2208 msgid "" "If a base that appears in a class definition is not an instance of :class:" "`type`, then an :meth:`!__mro_entries__` method is searched on the base. If " "an :meth:`!__mro_entries__` method is found, the base is substituted with " "the result of a call to :meth:`!__mro_entries__` when creating the class. " "The method is called with the original bases tuple passed to the *bases* " "parameter, and must return a tuple of classes that will be used instead of " "the base. The returned tuple may be empty: in these cases, the original base " "is ignored." msgstr "" "Si una base que aparece en una definición de clase no es una instancia de :" "class:`type`, entonces se busca un método :meth:`!__mro_entries__` en la " "base. Si se encuentra un método :meth:`!__mro_entries__`, la base se " "sustituye por el resultado de una llamada a :meth:`!__mro_entries__` al " "crear la clase. El método se llama con la tupla de bases original pasada al " "parámetro *bases* y debe retornar una tupla de clases que se utilizará en " "lugar de la base. La tupla retornada puede estar vacía: en estos casos, se " "ignora la base original." #: ../Doc/reference/datamodel.rst:2220 msgid ":func:`types.resolve_bases`" msgstr ":func:`types.resolve_bases`" #: ../Doc/reference/datamodel.rst:2220 msgid "Dynamically resolve bases that are not instances of :class:`type`." msgstr "Resuelva dinámicamente bases que no sean instancias de :class:`type`." #: ../Doc/reference/datamodel.rst:2224 msgid ":func:`types.get_original_bases`" msgstr ":func:`types.get_original_bases`" #: ../Doc/reference/datamodel.rst:2223 msgid "" "Retrieve a class's \"original bases\" prior to modifications by :meth:" "`~object.__mro_entries__`." msgstr "" "Recupera las \"bases originales\" de una clase antes de las modificaciones " "realizadas por :meth:`~object.__mro_entries__`." #: ../Doc/reference/datamodel.rst:2226 msgid ":pep:`560`" msgstr ":pep:`560`" #: ../Doc/reference/datamodel.rst:2227 msgid "Core support for typing module and generic types." msgstr "Soporte principal para módulos de escritura y tipos genéricos." #: ../Doc/reference/datamodel.rst:2231 msgid "Determining the appropriate metaclass" msgstr "Determinando la metaclase adecuada" #: ../Doc/reference/datamodel.rst:2235 msgid "" "The appropriate metaclass for a class definition is determined as follows:" msgstr "" "La metaclase adecuada para la definición de una clase es determinada de la " "siguiente manera:" #: ../Doc/reference/datamodel.rst:2237 msgid "" "if no bases and no explicit metaclass are given, then :func:`type` is used;" msgstr "" "si no se dan bases ni metaclases explícitas, entonces se utiliza :func:" "`type`;" #: ../Doc/reference/datamodel.rst:2238 msgid "" "if an explicit metaclass is given and it is *not* an instance of :func:" "`type`, then it is used directly as the metaclass;" msgstr "" "si se da una metaclase explícita y *no* es una instancia de :func:`type`, " "entonces se utiliza directamente como la metaclase;" #: ../Doc/reference/datamodel.rst:2240 msgid "" "if an instance of :func:`type` is given as the explicit metaclass, or bases " "are defined, then the most derived metaclass is used." msgstr "" "si se da una instancia de :func:`type` como la metaclase explícita, o se " "definen bases, entonces se utiliza la metaclase más derivada." #: ../Doc/reference/datamodel.rst:2243 msgid "" "The most derived metaclass is selected from the explicitly specified " "metaclass (if any) and the metaclasses (i.e. ``type(cls)``) of all specified " "base classes. The most derived metaclass is one which is a subtype of *all* " "of these candidate metaclasses. If none of the candidate metaclasses meets " "that criterion, then the class definition will fail with ``TypeError``." msgstr "" "La metaclase más derivada es elegida de la metaclase especificada " "explícitamente (si existe) y de la metaclase (p. ej. ``type(cls)``) de todas " "las clases base especificadas." #: ../Doc/reference/datamodel.rst:2253 msgid "Preparing the class namespace" msgstr "Preparando el espacio de nombres de la clase" #: ../Doc/reference/datamodel.rst:2258 msgid "" "Once the appropriate metaclass has been identified, then the class namespace " "is prepared. If the metaclass has a ``__prepare__`` attribute, it is called " "as ``namespace = metaclass.__prepare__(name, bases, **kwds)`` (where the " "additional keyword arguments, if any, come from the class definition). The " "``__prepare__`` method should be implemented as a :func:`classmethod " "`. The namespace returned by ``__prepare__`` is passed in to " "``__new__``, but when the final class object is created the namespace is " "copied into a new ``dict``." msgstr "" "Una vez que se ha identificado la metaclase adecuada, se prepara el espacio " "de nombres de la clase. Si la metaclase tiene un atributo ``__prepare__``, " "se llama ``namespace = metaclass.__prepare__(name, bases, **kwds)`` (donde " "los argumentos de palabras clave adicionales, si los hay, provienen de la " "definición de clase). El método ``__prepare__`` debe implementarse como :" "func:`classmethod `. El espacio de nombres retornado por " "``__prepare__`` se pasa a ``__new__``, pero cuando se crea el objeto de " "clase final, el espacio de nombres se copia en un nuevo ``dict``." #: ../Doc/reference/datamodel.rst:2267 msgid "" "If the metaclass has no ``__prepare__`` attribute, then the class namespace " "is initialised as an empty ordered mapping." msgstr "" "Si la metaclase no tiene atributo ``__prepare__``, entonces el espacio de " "nombres de clase es iniciado como un mapeo vacío ordenado." #: ../Doc/reference/datamodel.rst:2272 msgid ":pep:`3115` - Metaclasses in Python 3000" msgstr ":pep:`3115` - Metaclases en Python 3000" #: ../Doc/reference/datamodel.rst:2273 msgid "Introduced the ``__prepare__`` namespace hook" msgstr "Introduce el enlace de espacio de nombres ``__prepare__``" #: ../Doc/reference/datamodel.rst:2277 msgid "Executing the class body" msgstr "Ejecutando el cuerpo de la clase" #: ../Doc/reference/datamodel.rst:2282 msgid "" "The class body is executed (approximately) as ``exec(body, globals(), " "namespace)``. The key difference from a normal call to :func:`exec` is that " "lexical scoping allows the class body (including any methods) to reference " "names from the current and outer scopes when the class definition occurs " "inside a function." msgstr "" "El cuerpo de la clase es ejecutado como ``exec(body, globals(), namespace)`` " "(aproximadamente). La diferencia clave con un llamado normal a :func:`exec` " "es que el alcance léxico permite que el cuerpo de la clase (incluyendo " "cualquier método) haga referencia a nombres de los alcances actuales y " "externos cuando la definición de clase sucede dentro de la función." #: ../Doc/reference/datamodel.rst:2288 msgid "" "However, even when the class definition occurs inside the function, methods " "defined inside the class still cannot see names defined at the class scope. " "Class variables must be accessed through the first parameter of instance or " "class methods, or through the implicit lexically scoped ``__class__`` " "reference described in the next section." msgstr "" "Sin embargo, aún cuando la definición de clase sucede dentro de la función, " "los métodos definidos dentro de la clase aún no pueden ver nombres definidos " "dentro del alcance de la clase. Variables de clase deben ser accedidas a " "través del primer parámetro de instancia o métodos de clase, o a través de " "la referencia al léxico implícito ``__class__`` descrita en la siguiente " "sección." #: ../Doc/reference/datamodel.rst:2297 msgid "Creating the class object" msgstr "Creando el objeto de clase" #: ../Doc/reference/datamodel.rst:2304 msgid "" "Once the class namespace has been populated by executing the class body, the " "class object is created by calling ``metaclass(name, bases, namespace, " "**kwds)`` (the additional keywords passed here are the same as those passed " "to ``__prepare__``)." msgstr "" "Una vez que el espacio de nombres de la clase ha sido poblado al ejecutar el " "cuerpo de la clase, el objeto de clase es creado al llamar ``metaclass(name, " "bases, namespace, **kwds)`` (las palabras clave adicionales que se pasan " "aquí, son las mismas que aquellas pasadas en ``__prepare__``)." #: ../Doc/reference/datamodel.rst:2309 msgid "" "This class object is the one that will be referenced by the zero-argument " "form of :func:`super`. ``__class__`` is an implicit closure reference " "created by the compiler if any methods in a class body refer to either " "``__class__`` or ``super``. This allows the zero argument form of :func:" "`super` to correctly identify the class being defined based on lexical " "scoping, while the class or instance that was used to make the current call " "is identified based on the first argument passed to the method." msgstr "" "Este objeto de clase es el que será referenciado por la forma sin argumentos " "de :func:`super`. ``__class__`` es una referencia de cierre implícita creada " "por el compilador si cualquier método en el cuerpo de una clase se refiere " "tanto a ``__class__`` o ``super``. Esto permite que la forma sin argumentos " "de :func:`super` identifique correctamente la clase definida en base al " "alcance léxico, mientras la clase o instancia que fue utilizada para hacer " "el llamado actual es identificado en base al primer argumento que se pasa al " "método." #: ../Doc/reference/datamodel.rst:2319 msgid "" "In CPython 3.6 and later, the ``__class__`` cell is passed to the metaclass " "as a ``__classcell__`` entry in the class namespace. If present, this must " "be propagated up to the ``type.__new__`` call in order for the class to be " "initialised correctly. Failing to do so will result in a :exc:`RuntimeError` " "in Python 3.8." msgstr "" "En CPython 3.6 y posterior, la celda ``__class__`` se pasa a la metaclase " "como una entrada ``__classcell__`` en el espacio de nombres de la clase. En " "caso de existir, esto debe ser propagado hacia el llamado ``type.__new__`` " "para que la clase se inicie correctamente. No hacerlo resultará en un error :" "exc:`RuntimeError` en Python 3.8." #: ../Doc/reference/datamodel.rst:2325 msgid "" "When using the default metaclass :class:`type`, or any metaclass that " "ultimately calls ``type.__new__``, the following additional customization " "steps are invoked after creating the class object:" msgstr "" "Cuando se utiliza la metaclase por defecto :class:`type`, o cualquier " "metaclase que finalmente llama a ``type.__new__``, los siguientes pasos de " "personalización adicional son invocados después de crear el objeto de clase:" #: ../Doc/reference/datamodel.rst:2329 msgid "" "The ``type.__new__`` method collects all of the attributes in the class " "namespace that define a :meth:`~object.__set_name__` method;" msgstr "" "El método ``type.__new__`` recolecta todos los atributos en el espacio de " "nombres de la clase que definen un método :meth:`~object.__set_name__`;" #: ../Doc/reference/datamodel.rst:2331 msgid "" "Those ``__set_name__`` methods are called with the class being defined and " "the assigned name of that particular attribute;" msgstr "" "Esos métodos ``__set_name__`` son llamados con la clase siendo definida y el " "nombre de ese atributo particular asignado;" #: ../Doc/reference/datamodel.rst:2333 msgid "" "The :meth:`~object.__init_subclass__` hook is called on the immediate parent " "of the new class in its method resolution order." msgstr "" "El gancho :meth:`~object.__init_subclass__` llama al padre inmediato de la " "nueva clase en su orden de resolución del método." #: ../Doc/reference/datamodel.rst:2336 msgid "" "After the class object is created, it is passed to the class decorators " "included in the class definition (if any) and the resulting object is bound " "in the local namespace as the defined class." msgstr "" "Después de que el objeto de clase es creado, se pasa al decorador de clase " "incluido en su definición (si existe) y el objeto resultante es enlazado en " "el espacio de nombres local como la clase definida." #: ../Doc/reference/datamodel.rst:2340 msgid "" "When a new class is created by ``type.__new__``, the object provided as the " "namespace parameter is copied to a new ordered mapping and the original " "object is discarded. The new copy is wrapped in a read-only proxy, which " "becomes the :attr:`~object.__dict__` attribute of the class object." msgstr "" "Cuando una nueva clase es creada por ``type.__new__``, el objeto " "proporcionado como el parámetro de espacio de nombres es copiado a un " "trazado ordenado y el objeto original es descartado. La nueva copia es " "*envuelta* en un proxy de solo lectura, que se convierte en el atributo :" "attr:`~object.__dict__` del objeto de clase." #: ../Doc/reference/datamodel.rst:2347 msgid ":pep:`3135` - New super" msgstr ":pep:`3135` - Nuevo súper" #: ../Doc/reference/datamodel.rst:2348 msgid "Describes the implicit ``__class__`` closure reference" msgstr "Describe la referencia de cierre implícita ``__class__``" #: ../Doc/reference/datamodel.rst:2352 msgid "Uses for metaclasses" msgstr "Usos para metaclases" #: ../Doc/reference/datamodel.rst:2354 msgid "" "The potential uses for metaclasses are boundless. Some ideas that have been " "explored include enum, logging, interface checking, automatic delegation, " "automatic property creation, proxies, frameworks, and automatic resource " "locking/synchronization." msgstr "" "Los usos potenciales para metaclases son ilimitados. Algunas ideas que ya " "han sido exploradas incluyen enumeración, registros, revisión de interface, " "delegación automática, creación de propiedades automática, proxy, " "infraestructuras, y bloqueo/sincronización automática de recursos." #: ../Doc/reference/datamodel.rst:2361 msgid "Customizing instance and subclass checks" msgstr "Personalizando revisiones de instancia y subclase" #: ../Doc/reference/datamodel.rst:2363 msgid "" "The following methods are used to override the default behavior of the :func:" "`isinstance` and :func:`issubclass` built-in functions." msgstr "" "Los siguientes métodos son utilizados para anular el comportamiento por " "defecto de las funciones incorporadas :func:`isinstance` y :func:" "`issubclass`." #: ../Doc/reference/datamodel.rst:2366 msgid "" "In particular, the metaclass :class:`abc.ABCMeta` implements these methods " "in order to allow the addition of Abstract Base Classes (ABCs) as \"virtual " "base classes\" to any class or type (including built-in types), including " "other ABCs." msgstr "" "En particular, la metaclase :class:`abc.ABCMeta` implementa estos métodos " "para permitir la adición de Clases Base Abstractas (ABCs, por su nombre en " "inglés *Abstract Base Clases*) como “clases base virtuales” a cualquier " "clase o tipo (incluyendo tipos incorporados), incluyendo otros ABCs." #: ../Doc/reference/datamodel.rst:2373 msgid "" "Return true if *instance* should be considered a (direct or indirect) " "instance of *class*. If defined, called to implement ``isinstance(instance, " "class)``." msgstr "" "Retorna *true* si la instancia *instance* debe ser considerada una instancia " "(directa o indirecta) de clase *class*. De ser definida, es llamado para " "implementar ``isinstance(instance, class)``." #: ../Doc/reference/datamodel.rst:2380 msgid "" "Return true if *subclass* should be considered a (direct or indirect) " "subclass of *class*. If defined, called to implement ``issubclass(subclass, " "class)``." msgstr "" "Retorna *true* si la subclase *subclass* debe ser considerada una subclase " "(directa o indirecta) de clase *class*. De ser definida, es llamado para " "implementar ``issubclass(subclass, class)``." #: ../Doc/reference/datamodel.rst:2385 msgid "" "Note that these methods are looked up on the type (metaclass) of a class. " "They cannot be defined as class methods in the actual class. This is " "consistent with the lookup of special methods that are called on instances, " "only in this case the instance is itself a class." msgstr "" "Tome en cuenta que estos métodos son buscados en el tipo (metaclase) de una " "clase. No pueden ser definidos como métodos de clase en la clase actual. " "Esto es consistente con la búsqueda de métodos especiales que son llamados " "en instancias, solo en este caso la instancia es por sí misma una clase." #: ../Doc/reference/datamodel.rst:2396 msgid ":pep:`3119` - Introducing Abstract Base Classes" msgstr "" ":pep:`3119` - Introducción a Clases Base Abstractas (*Abstract Base Classes*)" #: ../Doc/reference/datamodel.rst:2393 msgid "" "Includes the specification for customizing :func:`isinstance` and :func:" "`issubclass` behavior through :meth:`~class.__instancecheck__` and :meth:" "`~class.__subclasscheck__`, with motivation for this functionality in the " "context of adding Abstract Base Classes (see the :mod:`abc` module) to the " "language." msgstr "" "Incluye la especificación para personalizar el comportamiento de :func:" "`isinstance` y :func:`issubclass` a través de :meth:`~class." "__instancecheck__` y :meth:`~class.__subclasscheck__`, con motivación para " "esta funcionalidad en el contexto de agregar Clases Base Abstractas (ver el " "módulo :mod:`abc`) al lenguaje." #: ../Doc/reference/datamodel.rst:2401 msgid "Emulating generic types" msgstr "Emulando tipos genéricos" #: ../Doc/reference/datamodel.rst:2403 msgid "" "When using :term:`type annotations`, it is often useful to " "*parameterize* a :term:`generic type` using Python's square-brackets " "notation. For example, the annotation ``list[int]`` might be used to signify " "a :class:`list` in which all the elements are of type :class:`int`." msgstr "" "Cuando se usa :term:`type annotations`, a menudo es útil " "*parameterize* a :term:`generic type` usando la notación de corchetes de " "Python. Por ejemplo, la anotación ``list[int]`` podría usarse para indicar " "un :class:`list` en el que todos los elementos son del tipo :class:`int`." #: ../Doc/reference/datamodel.rst:2411 msgid ":pep:`484` - Type Hints" msgstr ":pep:`484` - Sugerencias de tipo" #: ../Doc/reference/datamodel.rst:2411 msgid "Introducing Python's framework for type annotations" msgstr "Presentamos el marco de trabajo de Python para las anotaciones de tipo" #: ../Doc/reference/datamodel.rst:2414 msgid ":ref:`Generic Alias Types`" msgstr ":ref:`Generic Alias Types`" #: ../Doc/reference/datamodel.rst:2414 msgid "Documentation for objects representing parameterized generic classes" msgstr "" "Documentación para objetos que representan clases genéricas parametrizadas" #: ../Doc/reference/datamodel.rst:2417 msgid "" ":ref:`Generics`, :ref:`user-defined generics` and :" "class:`typing.Generic`" msgstr "" ":ref:`Generics`, :ref:`user-defined generics` y :" "class:`typing.Generic`" #: ../Doc/reference/datamodel.rst:2417 msgid "" "Documentation on how to implement generic classes that can be parameterized " "at runtime and understood by static type-checkers." msgstr "" "Documentación sobre cómo implementar clases genéricas que se pueden " "parametrizar en tiempo de ejecución y que los verificadores de tipos " "estáticos pueden entender." #: ../Doc/reference/datamodel.rst:2420 msgid "" "A class can *generally* only be parameterized if it defines the special " "class method ``__class_getitem__()``." msgstr "" "Una clase *generally* solo se puede parametrizar si define el método de " "clase especial ``__class_getitem__()``." #: ../Doc/reference/datamodel.rst:2425 msgid "" "Return an object representing the specialization of a generic class by type " "arguments found in *key*." msgstr "" "Retornar un objeto representando la especialización de una clase genérica " "por argumentos de tipo encontrados en *key*." #: ../Doc/reference/datamodel.rst:2428 msgid "" "When defined on a class, ``__class_getitem__()`` is automatically a class " "method. As such, there is no need for it to be decorated with :func:" "`@classmethod` when it is defined." msgstr "" "Cuando se define en una clase, ``__class_getitem__()`` es automáticamente un " "método de clase. Como tal, no es necesario decorarlo con :func:" "`@classmethod` cuando se define." #: ../Doc/reference/datamodel.rst:2434 msgid "The purpose of *__class_getitem__*" msgstr "El propósito de *__class_getitem__*" #: ../Doc/reference/datamodel.rst:2436 msgid "" "The purpose of :meth:`~object.__class_getitem__` is to allow runtime " "parameterization of standard-library generic classes in order to more easily " "apply :term:`type hints` to these classes." msgstr "" "El propósito de :meth:`~object.__class_getitem__` es permitir la " "parametrización en tiempo de ejecución de clases genéricas de biblioteca " "estándar para aplicar :term:`type hints` a estas clases con mayor " "facilidad." #: ../Doc/reference/datamodel.rst:2440 msgid "" "To implement custom generic classes that can be parameterized at runtime and " "understood by static type-checkers, users should either inherit from a " "standard library class that already implements :meth:`~object." "__class_getitem__`, or inherit from :class:`typing.Generic`, which has its " "own implementation of ``__class_getitem__()``." msgstr "" "Para implementar clases genéricas personalizadas que se puedan parametrizar " "en tiempo de ejecución y que los verificadores de tipos estáticos las " "entiendan, los usuarios deben heredar de una clase de biblioteca estándar " "que ya implementa :meth:`~object.__class_getitem__`, o heredar de :class:" "`typing.Generic`, que tiene su propia implementación de " "``__class_getitem__()``." #: ../Doc/reference/datamodel.rst:2446 msgid "" "Custom implementations of :meth:`~object.__class_getitem__` on classes " "defined outside of the standard library may not be understood by third-party " "type-checkers such as mypy. Using ``__class_getitem__()`` on any class for " "purposes other than type hinting is discouraged." msgstr "" "Es posible que los verificadores de tipos de terceros, como mypy, no " "entiendan las implementaciones personalizadas de :meth:`~object." "__class_getitem__` en clases definidas fuera de la biblioteca estándar. Se " "desaconseja el uso de ``__class_getitem__()`` en cualquier clase para fines " "distintos a la sugerencia de tipo." #: ../Doc/reference/datamodel.rst:2456 msgid "*__class_getitem__* versus *__getitem__*" msgstr "*__class_getitem__* frente a *__getitem__*" #: ../Doc/reference/datamodel.rst:2458 msgid "" "Usually, the :ref:`subscription` of an object using square " "brackets will call the :meth:`~object.__getitem__` instance method defined " "on the object's class. However, if the object being subscribed is itself a " "class, the class method :meth:`~object.__class_getitem__` may be called " "instead. ``__class_getitem__()`` should return a :ref:`GenericAlias` object if it is properly defined." msgstr "" "Por lo general, el :ref:`subscription` de un objeto que usa " "corchetes llamará al método de instancia :meth:`~object.__getitem__` " "definido en la clase del objeto. Sin embargo, si el objeto que se suscribe " "es en sí mismo una clase, se puede llamar al método de clase :meth:`~object." "__class_getitem__` en su lugar. ``__class_getitem__()`` debería retornar un " "objeto :ref:`GenericAlias` si está definido " "correctamente." #: ../Doc/reference/datamodel.rst:2465 msgid "" "Presented with the :term:`expression` ``obj[x]``, the Python interpreter " "follows something like the following process to decide whether :meth:" "`~object.__getitem__` or :meth:`~object.__class_getitem__` should be called::" msgstr "" "Presentado con el :term:`expression` ``obj[x]``, el intérprete de Python " "sigue un proceso similar al siguiente para decidir si se debe llamar a :meth:" "`~object.__getitem__` o :meth:`~object.__class_getitem__`:" #: ../Doc/reference/datamodel.rst:2493 msgid "" "In Python, all classes are themselves instances of other classes. The class " "of a class is known as that class's :term:`metaclass`, and most classes have " "the :class:`type` class as their metaclass. :class:`type` does not define :" "meth:`~object.__getitem__`, meaning that expressions such as ``list[int]``, " "``dict[str, float]`` and ``tuple[str, bytes]`` all result in :meth:`~object." "__class_getitem__` being called::" msgstr "" "En Python, todas las clases son en sí mismas instancias de otras clases. La " "clase de una clase se conoce como :term:`metaclass` de esa clase, y la " "mayoría de las clases tienen la clase :class:`type` como su metaclase. :" "class:`type` no define :meth:`~object.__getitem__`, lo que significa que " "expresiones como ``list[int]``, ``dict[str, float]`` y ``tuple[str, bytes]`` " "dan como resultado que se llame a :meth:`~object.__class_getitem__`:" #: ../Doc/reference/datamodel.rst:2512 msgid "" "However, if a class has a custom metaclass that defines :meth:`~object." "__getitem__`, subscribing the class may result in different behaviour. An " "example of this can be found in the :mod:`enum` module::" msgstr "" "Sin embargo, si una clase tiene una metaclase personalizada que define :meth:" "`~object.__getitem__`, la suscripción de la clase puede generar un " "comportamiento diferente. Un ejemplo de esto se puede encontrar en el " "módulo :mod:`enum`:" #: ../Doc/reference/datamodel.rst:2537 msgid ":pep:`560` - Core Support for typing module and generic types" msgstr "" ":pep:`560`: soporte principal para módulo de escritura y tipos genéricos" #: ../Doc/reference/datamodel.rst:2536 msgid "" "Introducing :meth:`~object.__class_getitem__`, and outlining when a :ref:" "`subscription` results in ``__class_getitem__()`` being " "called instead of :meth:`~object.__getitem__`" msgstr "" "Presentamos :meth:`~object.__class_getitem__` y describimos cuándo un :ref:" "`subscription` da como resultado que se llame a " "``__class_getitem__()`` en lugar de :meth:`~object.__getitem__`" #: ../Doc/reference/datamodel.rst:2544 msgid "Emulating callable objects" msgstr "Emulando objetos que se pueden llamar" #: ../Doc/reference/datamodel.rst:2551 msgid "" "Called when the instance is \"called\" as a function; if this method is " "defined, ``x(arg1, arg2, ...)`` roughly translates to ``type(x).__call__(x, " "arg1, ...)``." msgstr "" "Es llamado cuando la instancia es “llamada” como una función; si este método " "es definido, ``x(arg1, arg2, …)`` es una clave corta para ``x.__call__(arg1, " "arg2, …)``." #: ../Doc/reference/datamodel.rst:2558 msgid "Emulating container types" msgstr "Emulando tipos de contenedores" #: ../Doc/reference/datamodel.rst:2560 msgid "" "The following methods can be defined to implement container objects. " "Containers usually are :term:`sequences ` (such as :class:`lists " "` or :class:`tuples `) or :term:`mappings ` (like :" "class:`dictionaries `), but can represent other containers as well. " "The first set of methods is used either to emulate a sequence or to emulate " "a mapping; the difference is that for a sequence, the allowable keys should " "be the integers *k* for which ``0 <= k < N`` where *N* is the length of the " "sequence, or :class:`slice` objects, which define a range of items. It is " "also recommended that mappings provide the methods :meth:`keys`, :meth:" "`values`, :meth:`items`, :meth:`get`, :meth:`clear`, :meth:`setdefault`, :" "meth:`pop`, :meth:`popitem`, :meth:`!copy`, and :meth:`update` behaving " "similar to those for Python's standard :class:`dictionary ` objects. " "The :mod:`collections.abc` module provides a :class:`~collections.abc." "MutableMapping` :term:`abstract base class` to help create those methods " "from a base set of :meth:`~object.__getitem__`, :meth:`~object." "__setitem__`, :meth:`~object.__delitem__`, and :meth:`keys`. Mutable " "sequences should provide methods :meth:`append`, :meth:`count`, :meth:" "`index`, :meth:`extend`, :meth:`insert`, :meth:`pop`, :meth:`remove`, :meth:" "`reverse` and :meth:`sort`, like Python standard :class:`list` objects. " "Finally, sequence types should implement addition (meaning concatenation) " "and multiplication (meaning repetition) by defining the methods :meth:" "`~object.__add__`, :meth:`~object.__radd__`, :meth:`~object.__iadd__`, :meth:" "`~object.__mul__`, :meth:`~object.__rmul__` and :meth:`~object.__imul__` " "described below; they should not define other numerical operators. It is " "recommended that both mappings and sequences implement the :meth:`~object." "__contains__` method to allow efficient use of the ``in`` operator; for " "mappings, ``in`` should search the mapping's keys; for sequences, it should " "search through the values. It is further recommended that both mappings and " "sequences implement the :meth:`~object.__iter__` method to allow efficient " "iteration through the container; for mappings, :meth:`__iter__` should " "iterate through the object's keys; for sequences, it should iterate through " "the values." msgstr "" "Se pueden definir los siguientes métodos para implementar objetos " "contenedores. Los contenedores suelen ser :term:`sequences ` " "(como :class:`lists ` o :class:`tuples `) o :term:`mappings " "` (como :class:`dictionaries `), pero también pueden " "representar otros contenedores. El primer conjunto de métodos se utiliza " "para emular una secuencia o un mapeo; la diferencia es que para una " "secuencia, las claves permitidas deben ser los números enteros *k* para los " "cuales ``0 <= k < N`` donde *N* es la longitud de la secuencia, u objetos :" "class:`slice`, que definen un rango de elementos. También se recomienda que " "las asignaciones proporcionen los métodos :meth:`keys`, :meth:`values`, :" "meth:`items`, :meth:`get`, :meth:`clear`, :meth:`setdefault`, :meth:`pop`, :" "meth:`popitem`, :meth:`!copy` y :meth:`update` que se comportan de manera " "similar a los de los objetos :class:`dictionary ` estándar de Python. " "El módulo :mod:`collections.abc` proporciona un :class:`~collections.abc." "MutableMapping` :term:`abstract base class` para ayudar a crear esos métodos " "a partir de un conjunto básico de :meth:`~object.__getitem__`, :meth:" "`~object.__setitem__`, :meth:`~object.__delitem__` y :meth:`keys`. Las " "secuencias mutables deben proporcionar los métodos :meth:`append`, :meth:" "`count`, :meth:`index`, :meth:`extend`, :meth:`insert`, :meth:`pop`, :meth:" "`remove`, :meth:`reverse` y :meth:`sort`, como los objetos :class:`list` " "estándar de Python. Finalmente, los tipos de secuencia deben implementar la " "suma (es decir, concatenación) y la multiplicación (es decir, repetición) " "definiendo los métodos :meth:`~object.__add__`, :meth:`~object.__radd__`, :" "meth:`~object.__iadd__`, :meth:`~object.__mul__`, :meth:`~object.__rmul__` " "y :meth:`~object.__imul__` que se describen a continuación; no deben definir " "otros operadores numéricos. Se recomienda que tanto las asignaciones como " "las secuencias implementen el método :meth:`~object.__contains__` para " "permitir el uso eficiente del operador ``in``; para asignaciones, ``in`` " "debería buscar las claves de la asignación; para secuencias, debe buscar " "entre los valores. Se recomienda además que tanto las asignaciones como las " "secuencias implementen el método :meth:`~object.__iter__` para permitir una " "iteración eficiente a través del contenedor; para asignaciones, :meth:" "`__iter__` debe iterar a través de las claves del objeto; para secuencias, " "debe iterar a través de los valores." #: ../Doc/reference/datamodel.rst:2600 msgid "" "Called to implement the built-in function :func:`len`. Should return the " "length of the object, an integer ``>=`` 0. Also, an object that doesn't " "define a :meth:`~object.__bool__` method and whose :meth:`!__len__` method " "returns zero is considered to be false in a Boolean context." msgstr "" "Llamado para implementar la función incorporada :func:`len`. Debería " "retornar la longitud del objeto, un número entero ``>=`` 0. Además, un " "objeto que no define un método :meth:`~object.__bool__` y cuyo método :meth:" "`!__len__` retorna cero se considera falso en un contexto booleano." #: ../Doc/reference/datamodel.rst:2607 msgid "" "In CPython, the length is required to be at most :data:`sys.maxsize`. If the " "length is larger than :data:`!sys.maxsize` some features (such as :func:" "`len`) may raise :exc:`OverflowError`. To prevent raising :exc:`!" "OverflowError` by truth value testing, an object must define a :meth:" "`~object.__bool__` method." msgstr "" "En CPython, se requiere que la longitud sea como máximo :data:`sys.maxsize`. " "Si la longitud es mayor que :data:`!sys.maxsize`, algunas funciones (como :" "func:`len`) pueden generar :exc:`OverflowError`. Para evitar que se genere :" "exc:`!OverflowError` mediante pruebas de valor de verdad, un objeto debe " "definir un método :meth:`~object.__bool__`." #: ../Doc/reference/datamodel.rst:2616 msgid "" "Called to implement :func:`operator.length_hint`. Should return an estimated " "length for the object (which may be greater or less than the actual length). " "The length must be an integer ``>=`` 0. The return value may also be :const:" "`NotImplemented`, which is treated the same as if the ``__length_hint__`` " "method didn't exist at all. This method is purely an optimization and is " "never required for correctness." msgstr "" "Es llamado para implementar :func:`operator.length_hint`. Debe retornar una " "longitud estimada para el objeto (que puede ser mayor o menor que la " "longitud actual). La longitud debe ser un entero ``>=`` 0. El valor de " "retorno también debe ser :const:`NotImplemented` el cual es tratado de igual " "forma a que si el método ``__length_hint__`` no existiera en absoluto. Este " "método es puramente una optimización y nunca es requerido para precisión." #: ../Doc/reference/datamodel.rst:2630 msgid "" "Slicing is done exclusively with the following three methods. A call like ::" msgstr "" "La segmentación se hace exclusivamente con los siguientes tres métodos. Un " "llamado como ::" #: ../Doc/reference/datamodel.rst:2634 msgid "is translated to ::" msgstr "es traducido a ::" #: ../Doc/reference/datamodel.rst:2638 msgid "and so forth. Missing slice items are always filled in with ``None``." msgstr "" "etcétera. Elementos faltantes de segmentos siempre son llenados con ``None``." #: ../Doc/reference/datamodel.rst:2643 msgid "" "Called to implement evaluation of ``self[key]``. For :term:`sequence` types, " "the accepted keys should be integers and slice objects. Note that the " "special interpretation of negative indexes (if the class wishes to emulate " "a :term:`sequence` type) is up to the :meth:`__getitem__` method. If *key* " "is of an inappropriate type, :exc:`TypeError` may be raised; if of a value " "outside the set of indexes for the sequence (after any special " "interpretation of negative values), :exc:`IndexError` should be raised. For :" "term:`mapping` types, if *key* is missing (not in the container), :exc:" "`KeyError` should be raised." msgstr "" "Llamado a implementar evaluación de ``self[key]``. Para los tipos :term:" "`sequence`, las claves aceptadas deben ser números enteros y objetos de " "segmento. Tenga en cuenta que la interpretación especial de los índices " "negativos (si la clase desea emular un tipo :term:`sequence`) depende del " "método :meth:`__getitem__`. Si *key* es de un tipo inadecuado, es posible " "que se genere :exc:`TypeError`; si se trata de un valor fuera del conjunto " "de índices de la secuencia (después de cualquier interpretación especial de " "valores negativos), se debe generar :exc:`IndexError`. Para los tipos :term:" "`mapping`, si falta *key* (no en el contenedor), se debe generar :exc:" "`KeyError`." #: ../Doc/reference/datamodel.rst:2655 msgid "" ":keyword:`for` loops expect that an :exc:`IndexError` will be raised for " "illegal indexes to allow proper detection of the end of the sequence." msgstr "" "ciclos :keyword:`for` esperan que una excepción :exc:`IndexError` sea " "lanzada para que índices ilegales permitan la detección adecuada del fin de " "una secuencia." #: ../Doc/reference/datamodel.rst:2660 msgid "" "When :ref:`subscripting` a *class*, the special class method :" "meth:`~object.__class_getitem__` may be called instead of ``__getitem__()``. " "See :ref:`classgetitem-versus-getitem` for more details." msgstr "" "Cuando :ref:`subscripting` a *class*, se puede llamar al " "método de clase especial :meth:`~object.__class_getitem__` en lugar de " "``__getitem__()``. Ver :ref:`classgetitem-versus-getitem` para más detalles." #: ../Doc/reference/datamodel.rst:2668 msgid "" "Called to implement assignment to ``self[key]``. Same note as for :meth:" "`__getitem__`. This should only be implemented for mappings if the objects " "support changes to the values for keys, or if new keys can be added, or for " "sequences if elements can be replaced. The same exceptions should be raised " "for improper *key* values as for the :meth:`__getitem__` method." msgstr "" "Es llamado para implementar la asignación a ``self[key]``. Lo mismo con " "respecto a :meth:`__getitem__`. Esto solo debe ser implementado para mapeos " "si los objetos permiten cambios a los valores de las llaves, o si nuevas " "llaves pueden ser añadidas, o para secuencias si los elementos pueden ser " "reemplazados. Las mismas excepciones deben ser lanzadas para valores de " "*key* inadecuados con respecto al método :meth:`__getitem__`." #: ../Doc/reference/datamodel.rst:2677 msgid "" "Called to implement deletion of ``self[key]``. Same note as for :meth:" "`__getitem__`. This should only be implemented for mappings if the objects " "support removal of keys, or for sequences if elements can be removed from " "the sequence. The same exceptions should be raised for improper *key* " "values as for the :meth:`__getitem__` method." msgstr "" "Es llamado para implementar el borrado de ``self[key]``. Lo mismo con " "respecto a :meth:`__getitem__`. Esto solo debe ser implementado para mapeos " "si los objetos permiten el borrado de llaves, o para secuencias si los " "elementos pueden ser eliminados de la secuencia. Las mismas excepciones " "deben ser lanzadas por valores de *key* inapropiados con respecto al método :" "meth:`__getitem__`." #: ../Doc/reference/datamodel.rst:2686 msgid "" "Called by :class:`dict`\\ .\\ :meth:`__getitem__` to implement ``self[key]`` " "for dict subclasses when key is not in the dictionary." msgstr "" "Es llamado por :class:`dict`\\ .\\ :meth:`__getitem__` para implementar " "``self[key]`` para subclases de diccionarios cuando la llave no se encuentra " "en el diccionario." #: ../Doc/reference/datamodel.rst:2692 msgid "" "This method is called when an :term:`iterator` is required for a container. " "This method should return a new iterator object that can iterate over all " "the objects in the container. For mappings, it should iterate over the keys " "of the container." msgstr "" "Se llama a este método cuando se requiere un :term:`iterator` para un " "contenedor. Este método debería retornar un nuevo objeto iterador que pueda " "iterar sobre todos los objetos del contenedor. Para las asignaciones, debe " "iterar sobre las claves del contenedor." #: ../Doc/reference/datamodel.rst:2700 msgid "" "Called (if present) by the :func:`reversed` built-in to implement reverse " "iteration. It should return a new iterator object that iterates over all " "the objects in the container in reverse order." msgstr "" "Es llamado (si existe) por la función incorporada :func:`reversed` para " "implementar una interacción invertida. Debe retornar un nuevo objeto " "iterador que itere sobre todos los objetos en el contenedor en orden inverso." #: ../Doc/reference/datamodel.rst:2704 msgid "" "If the :meth:`__reversed__` method is not provided, the :func:`reversed` " "built-in will fall back to using the sequence protocol (:meth:`__len__` and :" "meth:`__getitem__`). Objects that support the sequence protocol should only " "provide :meth:`__reversed__` if they can provide an implementation that is " "more efficient than the one provided by :func:`reversed`." msgstr "" "Si el método :meth:`__reversed__` no es proporcionado, la función " "incorporada :func:`reversed` recurrirá a utilizar el protocolo de secuencia " "(:meth:`__len__` y :meth:`__getitem__`). Objetos que permiten el protocolo " "de secuencia deben únicamente proporcionar :meth:`__reversed__` si no pueden " "proporcionar una implementación que sea más eficiente que la proporcionada " "por :func:`reversed`." #: ../Doc/reference/datamodel.rst:2711 msgid "" "The membership test operators (:keyword:`in` and :keyword:`not in`) are " "normally implemented as an iteration through a container. However, container " "objects can supply the following special method with a more efficient " "implementation, which also does not require the object be iterable." msgstr "" "Los operadores de prueba de pertenencia (:keyword:`in` and :keyword:`not " "in`) son normalmente implementados como una iteración sobre un contenedor. " "Sin embargo, los objetos de contenedor pueden proveer el siguiente método " "especial con una implementación más eficiente, que tampoco requiere que el " "objeto sea iterable." #: ../Doc/reference/datamodel.rst:2718 msgid "" "Called to implement membership test operators. Should return true if *item* " "is in *self*, false otherwise. For mapping objects, this should consider " "the keys of the mapping rather than the values or the key-item pairs." msgstr "" "Es llamado para implementar operadores de prueba de pertenencia. Deben " "retornar *true* si *item* se encuentra en *self*, de lo contrario *false*. " "Para objetos de mapeo, estos debe considerar las llaves del mapeo en lugar " "de los valores o los pares de llave-valor." #: ../Doc/reference/datamodel.rst:2722 msgid "" "For objects that don't define :meth:`__contains__`, the membership test " "first tries iteration via :meth:`__iter__`, then the old sequence iteration " "protocol via :meth:`__getitem__`, see :ref:`this section in the language " "reference `." msgstr "" "Para objetos que no definen :meth:`__contains__`, la prueba de pertenencia " "primero intenta la iteración a través de :meth:`__iter__`, y luego el " "antiguo protocolo de iteración de secuencia a través de :meth:`__getitem__`, " "ver :ref:`esta sección en la referencia del lenguaje `." #: ../Doc/reference/datamodel.rst:2731 msgid "Emulating numeric types" msgstr "Emulando tipos numéricos" #: ../Doc/reference/datamodel.rst:2733 msgid "" "The following methods can be defined to emulate numeric objects. Methods " "corresponding to operations that are not supported by the particular kind of " "number implemented (e.g., bitwise operations for non-integral numbers) " "should be left undefined." msgstr "" "Los siguientes métodos pueden ser definidos para emular objetos numéricos. " "Métodos que corresponden a operaciones que no son permitidas por el número " "particular implementado (por ejemplo, operaciones bit a bit para números no " "enteros) se deben dejar sin definir." #: ../Doc/reference/datamodel.rst:2759 msgid "" "These methods are called to implement the binary arithmetic operations " "(``+``, ``-``, ``*``, ``@``, ``/``, ``//``, ``%``, :func:`divmod`, :func:" "`pow`, ``**``, ``<<``, ``>>``, ``&``, ``^``, ``|``). For instance, to " "evaluate the expression ``x + y``, where *x* is an instance of a class that " "has an :meth:`__add__` method, ``type(x).__add__(x, y)`` is called. The :" "meth:`__divmod__` method should be the equivalent to using :meth:" "`__floordiv__` and :meth:`__mod__`; it should not be related to :meth:" "`__truediv__`. Note that :meth:`__pow__` should be defined to accept an " "optional third argument if the ternary version of the built-in :func:`pow` " "function is to be supported." msgstr "" "Estos métodos se llaman para implementar las operaciones aritméticas " "binarias (``+``, ``-``, ``*``, ``@``, ``/``, ``//``, ``%``, :func:`divmod`, :" "func:`pow`, ``**``, ``<<``, ``>>``, ``&``, ``^``, ``|``). Por ejemplo, para " "evaluar la expresión ``x + y``, donde *x* es una instancia de una clase que " "tiene un método :meth:`__add__`, se llama a ``type(x).__add__(x, y)``. El " "método :meth:`__divmod__` debería ser equivalente al uso de :meth:" "`__floordiv__` y :meth:`__mod__`; no debería estar relacionado con :meth:" "`__truediv__`. Tenga en cuenta que :meth:`__pow__` debe definirse para " "aceptar un tercer argumento opcional si se va a admitir la versión ternaria " "de la función incorporada :func:`pow`." #: ../Doc/reference/datamodel.rst:2770 msgid "" "If one of those methods does not support the operation with the supplied " "arguments, it should return ``NotImplemented``." msgstr "" "Si alguno de esos métodos no permiten la operación con los argumentos " "suministrados, debe retornar ``NotImplemented``." #: ../Doc/reference/datamodel.rst:2793 msgid "" "These methods are called to implement the binary arithmetic operations " "(``+``, ``-``, ``*``, ``@``, ``/``, ``//``, ``%``, :func:`divmod`, :func:" "`pow`, ``**``, ``<<``, ``>>``, ``&``, ``^``, ``|``) with reflected (swapped) " "operands. These functions are only called if the left operand does not " "support the corresponding operation [#]_ and the operands are of different " "types. [#]_ For instance, to evaluate the expression ``x - y``, where *y* is " "an instance of a class that has an :meth:`__rsub__` method, ``type(y)." "__rsub__(y, x)`` is called if ``type(x).__sub__(x, y)`` returns " "*NotImplemented*." msgstr "" "Estos métodos se llaman para implementar las operaciones aritméticas " "binarias (``+``, ``-``, ``*``, ``@``, ``/``, ``//``, ``%``, :func:`divmod`, :" "func:`pow`, ``**``, ``<<``, ``>>``, ``&``, ``^``, ``|``) con operandos " "reflejados (intercambiados). Estas funciones solo se llaman si el operando " "izquierdo no admite la operación correspondiente [#]_ y los operandos son de " "diferentes tipos. [#]_ Por ejemplo, para evaluar la expresión ``x - y``, " "donde *y* es una instancia de una clase que tiene un método :meth:" "`__rsub__`, se llama a ``type(y).__rsub__(y, x)`` si ``type(x).__sub__(x, " "y)`` retorna *NotImplemented*." #: ../Doc/reference/datamodel.rst:2805 msgid "" "Note that ternary :func:`pow` will not try calling :meth:`__rpow__` (the " "coercion rules would become too complicated)." msgstr "" "Se debe tomar en cuenta que la función ternaria :func:`pow` no intentará " "llamar a :meth:`__rpow__` (las reglas de coerción se volverían demasiado " "complicadas)." #: ../Doc/reference/datamodel.rst:2810 msgid "" "If the right operand's type is a subclass of the left operand's type and " "that subclass provides a different implementation of the reflected method " "for the operation, this method will be called before the left operand's non-" "reflected method. This behavior allows subclasses to override their " "ancestors' operations." msgstr "" "Si el tipo del operando de la derecha es una subclase del tipo del operando " "de la izquierda y esa subclase proporciona el método reflejado para la " "operación, este método será llamado antes del método no reflejado del " "operando izquierdo. Este comportamiento permite que las subclases anulen las " "operaciones de sus predecesores." #: ../Doc/reference/datamodel.rst:2831 msgid "" "These methods are called to implement the augmented arithmetic assignments " "(``+=``, ``-=``, ``*=``, ``@=``, ``/=``, ``//=``, ``%=``, ``**=``, ``<<=``, " "``>>=``, ``&=``, ``^=``, ``|=``). These methods should attempt to do the " "operation in-place (modifying *self*) and return the result (which could be, " "but does not have to be, *self*). If a specific method is not defined, the " "augmented assignment falls back to the normal methods. For instance, if *x* " "is an instance of a class with an :meth:`__iadd__` method, ``x += y`` is " "equivalent to ``x = x.__iadd__(y)`` . Otherwise, ``x.__add__(y)`` and ``y." "__radd__(x)`` are considered, as with the evaluation of ``x + y``. In " "certain situations, augmented assignment can result in unexpected errors " "(see :ref:`faq-augmented-assignment-tuple-error`), but this behavior is in " "fact part of the data model." msgstr "" "Estos métodos son llamados para implementar las asignaciones aritméticas " "aumentadas (``+=``, ``-=``, ``*=``, ``@=``, ``/=``, ``//=``, ``%=``, " "``**=``, ``<<=``, ``>>=``, ``&=``, ``^=``, ``|=``). Estos métodos deben " "intentar realizar la operación *in-place* (modificando *self*) y retornar el " "resultado (que puede, pero no tiene que ser *self*). Si un método específico " "no es definido, la asignación aumentada regresa a los métodos normales. Por " "ejemplo, si *x* es la instancia de una clase con el método :meth:`__iadd__`, " "``x += y`` es equivalente a ``x = x.__iadd__(y)``. De lo contrario ``x." "__add__(y)`` y ``y.__radd__(x)`` se consideran al igual que con la " "evaluación de ``x + y``. En ciertas situaciones, asignaciones aumentadas " "pueden resultar en errores no esperados (ver :ref:`faq-augmented-assignment-" "tuple-error`), pero este comportamiento es en realidad parte del modelo de " "datos." #: ../Doc/reference/datamodel.rst:2852 msgid "" "Called to implement the unary arithmetic operations (``-``, ``+``, :func:" "`abs` and ``~``)." msgstr "" "Es llamado para implementar las operaciones aritméticas unarias (``-``, " "``+``, :func:`abs` and ``~``)." #: ../Doc/reference/datamodel.rst:2865 msgid "" "Called to implement the built-in functions :func:`complex`, :func:`int` and :" "func:`float`. Should return a value of the appropriate type." msgstr "" "Es llamado para implementar las funciones incorporadas :func:`complex`, :" "func:`int` y :func:`float`. Debe retornar un valor del tipo apropiado." #: ../Doc/reference/datamodel.rst:2872 msgid "" "Called to implement :func:`operator.index`, and whenever Python needs to " "losslessly convert the numeric object to an integer object (such as in " "slicing, or in the built-in :func:`bin`, :func:`hex` and :func:`oct` " "functions). Presence of this method indicates that the numeric object is an " "integer type. Must return an integer." msgstr "" "Es llamado para implementar :func:`operator.index`, y cuando sea que Python " "necesite convertir sin pérdidas el objeto numérico a un objeto entero (tal " "como en la segmentación o *slicing*, o las funciones incorporadas :func:" "`bin`, :func:`hex` y :func:`oct`). La presencia de este método indica que el " "objeto numérico es un tipo entero. Debe retornar un entero." #: ../Doc/reference/datamodel.rst:2878 msgid "" "If :meth:`__int__`, :meth:`__float__` and :meth:`__complex__` are not " "defined then corresponding built-in functions :func:`int`, :func:`float` " "and :func:`complex` fall back to :meth:`__index__`." msgstr "" "Si :meth:`__int__`, :meth:`__float__` y :meth:`__complex__` no son " "definidos, entonces todas las funciones incorporadas correspondientes :func:" "`int`, :func:`float` y :func:`complex` vuelven a :meth:`__index__`." #: ../Doc/reference/datamodel.rst:2890 msgid "" "Called to implement the built-in function :func:`round` and :mod:`math` " "functions :func:`~math.trunc`, :func:`~math.floor` and :func:`~math.ceil`. " "Unless *ndigits* is passed to :meth:`!__round__` all these methods should " "return the value of the object truncated to an :class:`~numbers.Integral` " "(typically an :class:`int`)." msgstr "" "Es llamado para implementar la función incorporada :func:`round` y las " "funciones :mod:`math` :func:`~math.trunc`, :func:`~math.floor` y :func:" "`~math.ceil`. A menos que *ndigits* sea pasado a :meth:`!__round__` todos " "estos métodos deben retornar el valor del objeto truncado a :class:`~numbers." "Integral` (normalmente :class:`int`)." #: ../Doc/reference/datamodel.rst:2896 msgid "" "The built-in function :func:`int` falls back to :meth:`__trunc__` if " "neither :meth:`__int__` nor :meth:`__index__` is defined." msgstr "" "La función integrada :func:`int` recurre a :meth:`__trunc__` si no se " "definen ni :meth:`__int__` ni :meth:`__index__`." #: ../Doc/reference/datamodel.rst:2899 msgid "The delegation of :func:`int` to :meth:`__trunc__` is deprecated." msgstr "La delegación de :func:`int` a :meth:`__trunc__` está obsoleta." #: ../Doc/reference/datamodel.rst:2906 msgid "With Statement Context Managers" msgstr "Gestores de Contexto en la Declaración *with*" #: ../Doc/reference/datamodel.rst:2908 msgid "" "A :dfn:`context manager` is an object that defines the runtime context to be " "established when executing a :keyword:`with` statement. The context manager " "handles the entry into, and the exit from, the desired runtime context for " "the execution of the block of code. Context managers are normally invoked " "using the :keyword:`!with` statement (described in section :ref:`with`), but " "can also be used by directly invoking their methods." msgstr "" "Un :dfn:`context manager` es un objeto que define el contexto en tiempo de " "ejecución a ser establecido cuando se ejecuta una declaración :keyword:" "`with`. El gestor de contexto maneja la entrada y la salida del contexto en " "tiempo de ejecución deseado para la ejecución del bloque de código. Los " "gestores de contexto son normalmente invocados utilizando la declaración :" "keyword:`!with` (descritos en la sección :ref:`with`), pero también pueden " "ser utilizados al invocar directamente sus métodos." #: ../Doc/reference/datamodel.rst:2919 msgid "" "Typical uses of context managers include saving and restoring various kinds " "of global state, locking and unlocking resources, closing opened files, etc." msgstr "" "Usos típicos de los gestores de contexto incluyen guardar y restablecer " "diversos tipos de declaraciones globales, bloquear y desbloquear recursos, " "cerrar archivos abiertos, etc." #: ../Doc/reference/datamodel.rst:2922 msgid "" "For more information on context managers, see :ref:`typecontextmanager`." msgstr "" "Para más información sobre gestores de contexto, ver :ref:" "`typecontextmanager`." #: ../Doc/reference/datamodel.rst:2927 msgid "" "Enter the runtime context related to this object. The :keyword:`with` " "statement will bind this method's return value to the target(s) specified in " "the :keyword:`!as` clause of the statement, if any." msgstr "" "Ingresa al contexto en tiempo de ejecución relacionado con este objeto. La " "declaración :keyword:`with` ligará el valor de retorno de este método al " "objetivo especificado en cláusula :keyword:`!as` de la declaración, en caso " "de existir." #: ../Doc/reference/datamodel.rst:2934 msgid "" "Exit the runtime context related to this object. The parameters describe the " "exception that caused the context to be exited. If the context was exited " "without an exception, all three arguments will be :const:`None`." msgstr "" "Sale del contexto en tiempo de ejecución relacionado a este objeto. Los " "parámetros describen la excepción que causa la salida del contexto. Si éste " "se termina sin excepción, los tres argumentos serán :const:`None`." #: ../Doc/reference/datamodel.rst:2938 msgid "" "If an exception is supplied, and the method wishes to suppress the exception " "(i.e., prevent it from being propagated), it should return a true value. " "Otherwise, the exception will be processed normally upon exit from this " "method." msgstr "" "Si se proporciona una excepción, y el método desea eliminarla (por ejemplo, " "prevenir que sea propagada), debe retornar un valor verdadero. De lo " "contrario, la excepción será procesada de forma normal al salir de este " "método." #: ../Doc/reference/datamodel.rst:2942 msgid "" "Note that :meth:`__exit__` methods should not reraise the passed-in " "exception; this is the caller's responsibility." msgstr "" "Se debe tomar en cuenta que los métodos :meth:`__exit__` no deben lanzar de " "nuevo la excepción que se pasa; esto es la responsabilidad de quien hace el " "llamado." #: ../Doc/reference/datamodel.rst:2949 msgid ":pep:`343` - The \"with\" statement" msgstr ":pep:`343` - La declaración “with”" #: ../Doc/reference/datamodel.rst:2949 msgid "" "The specification, background, and examples for the Python :keyword:`with` " "statement." msgstr "" "La especificación, el antecedente, y los ejemplos para la declaración de " "Python :keyword:`with`." #: ../Doc/reference/datamodel.rst:2956 msgid "Customizing positional arguments in class pattern matching" msgstr "" "Personalización de argumentos posicionales en la coincidencia de patrones de " "clase" #: ../Doc/reference/datamodel.rst:2958 msgid "" "When using a class name in a pattern, positional arguments in the pattern " "are not allowed by default, i.e. ``case MyClass(x, y)`` is typically invalid " "without special support in ``MyClass``. To be able to use that kind of " "pattern, the class needs to define a *__match_args__* attribute." msgstr "" "Cuando se utiliza un nombre de clase en un patrón, los argumentos " "posicionales en el patrón no están permitidos de forma predeterminada, es " "decir, ``case MyClass(x, y)`` normalmente no es válido sin un soporte " "especial en ``MyClass``. Para poder utilizar ese tipo de patrón, la clase " "necesita definir un atributo *__match_args__*." #: ../Doc/reference/datamodel.rst:2965 msgid "" "This class variable can be assigned a tuple of strings. When this class is " "used in a class pattern with positional arguments, each positional argument " "will be converted into a keyword argument, using the corresponding value in " "*__match_args__* as the keyword. The absence of this attribute is equivalent " "to setting it to ``()``." msgstr "" "A esta variable de clase se le puede asignar una tupla de cadenas. Cuando " "esta clase se utiliza en un patrón de clase con argumentos posicionales, " "cada argumento posicional se convertirá en un argumento de palabra clave, " "utilizando el valor correspondiente en *__match_args__* como palabra clave. " "La ausencia de este atributo es equivalente a establecerlo en ``()``." #: ../Doc/reference/datamodel.rst:2971 msgid "" "For example, if ``MyClass.__match_args__`` is ``(\"left\", \"center\", " "\"right\")`` that means that ``case MyClass(x, y)`` is equivalent to ``case " "MyClass(left=x, center=y)``. Note that the number of arguments in the " "pattern must be smaller than or equal to the number of elements in " "*__match_args__*; if it is larger, the pattern match attempt will raise a :" "exc:`TypeError`." msgstr "" "Por ejemplo, si ``MyClass.__match_args__`` es ``(\"left\", \"center\", " "\"right\")`` eso significa que ``case MyClass(x, y)`` es equivalente a " "``case MyClass(left=x, center=y)``. Ten en cuenta que el número de " "argumentos en el patrón debe ser menor o igual que el número de elementos en " "*__match_args__*; si es más grande, el intento de coincidencia de patrón " "producirá un :exc:`TypeError`." #: ../Doc/reference/datamodel.rst:2981 msgid ":pep:`634` - Structural Pattern Matching" msgstr ":pep:`634` - Coincidencia de patrones estructurales" #: ../Doc/reference/datamodel.rst:2982 msgid "The specification for the Python ``match`` statement." msgstr "La especificación para la declaración ``match`` de Python." #: ../Doc/reference/datamodel.rst:2988 msgid "Emulating buffer types" msgstr "Emulando tipos de búfer" #: ../Doc/reference/datamodel.rst:2990 msgid "" "The :ref:`buffer protocol ` provides a way for Python objects " "to expose efficient access to a low-level memory array. This protocol is " "implemented by builtin types such as :class:`bytes` and :class:`memoryview`, " "and third-party libraries may define additional buffer types." msgstr "" ":ref:`buffer protocol ` proporciona una forma para que los " "objetos Python expongan un acceso eficiente a una matriz de memoria de bajo " "nivel. Este protocolo se implementa mediante tipos integrados como :class:" "`bytes` y :class:`memoryview`, y bibliotecas de terceros pueden definir " "tipos de búfer adicionales." #: ../Doc/reference/datamodel.rst:2995 msgid "" "While buffer types are usually implemented in C, it is also possible to " "implement the protocol in Python." msgstr "" "Si bien los tipos de búfer generalmente se implementan en C, también es " "posible implementar el protocolo en Python." #: ../Doc/reference/datamodel.rst:3000 msgid "" "Called when a buffer is requested from *self* (for example, by the :class:" "`memoryview` constructor). The *flags* argument is an integer representing " "the kind of buffer requested, affecting for example whether the returned " "buffer is read-only or writable. :class:`inspect.BufferFlags` provides a " "convenient way to interpret the flags. The method must return a :class:" "`memoryview` object." msgstr "" "Se llama cuando se solicita un búfer desde *self* (por ejemplo, por el " "constructor :class:`memoryview`). El argumento *flags* es un número entero " "que representa el tipo de búfer solicitado y afecta, por ejemplo, si el " "búfer retornado es de solo lectura o de escritura. :class:`inspect." "BufferFlags` proporciona una manera conveniente de interpretar las banderas. " "El método debe retornar un objeto :class:`memoryview`." #: ../Doc/reference/datamodel.rst:3009 msgid "" "Called when a buffer is no longer needed. The *buffer* argument is a :class:" "`memoryview` object that was previously returned by :meth:`~object." "__buffer__`. The method must release any resources associated with the " "buffer. This method should return ``None``. Buffer objects that do not need " "to perform any cleanup are not required to implement this method." msgstr "" "Se llama cuando ya no se necesita un búfer. El argumento *buffer* es un " "objeto :class:`memoryview` que :meth:`~object.__buffer__` retornó " "anteriormente. El método debe liberar todos los recursos asociados con el " "búfer. Este método debería retornar ``None``. Los objetos de búfer que no " "necesitan realizar ninguna limpieza no son necesarios para implementar este " "método." #: ../Doc/reference/datamodel.rst:3021 msgid ":pep:`688` - Making the buffer protocol accessible in Python" msgstr ":pep:`688`: hacer accesible el protocolo de búfer en Python" #: ../Doc/reference/datamodel.rst:3021 msgid "" "Introduces the Python ``__buffer__`` and ``__release_buffer__`` methods." msgstr "Presenta los métodos Python ``__buffer__`` y ``__release_buffer__``." #: ../Doc/reference/datamodel.rst:3023 msgid ":class:`collections.abc.Buffer`" msgstr ":class:`collections.abc.Buffer`" #: ../Doc/reference/datamodel.rst:3024 msgid "ABC for buffer types." msgstr "ABC para tipos de buffer." #: ../Doc/reference/datamodel.rst:3029 msgid "Special method lookup" msgstr "Búsqueda de método especial" #: ../Doc/reference/datamodel.rst:3031 msgid "" "For custom classes, implicit invocations of special methods are only " "guaranteed to work correctly if defined on an object's type, not in the " "object's instance dictionary. That behaviour is the reason why the " "following code raises an exception::" msgstr "" "Para clases personalizadas, invocaciones implícitas de métodos especiales " "solo están garantizados para trabajar correctamente si son definidos en un " "tipo de objeto, no en el diccionario de instancia del objeto. Ese " "comportamiento es la razón por la que el siguiente código lanza una " "excepción::" #: ../Doc/reference/datamodel.rst:3046 msgid "" "The rationale behind this behaviour lies with a number of special methods " "such as :meth:`~object.__hash__` and :meth:`~object.__repr__` that are " "implemented by all objects, including type objects. If the implicit lookup " "of these methods used the conventional lookup process, they would fail when " "invoked on the type object itself::" msgstr "" "La razón detrás de este comportamiento radica en una serie de métodos " "especiales, como :meth:`~object.__hash__` y :meth:`~object.__repr__`, que " "implementan todos los objetos, incluidos los objetos de tipo. Si la búsqueda " "implícita de estos métodos utilizara el proceso de búsqueda convencional, " "fallarían cuando se invocaran en el objeto de tipo mismo:" #: ../Doc/reference/datamodel.rst:3060 msgid "" "Incorrectly attempting to invoke an unbound method of a class in this way is " "sometimes referred to as 'metaclass confusion', and is avoided by bypassing " "the instance when looking up special methods::" msgstr "" "Intentar invocar de manera incorrecta el método no ligado de una clase de " "esta forma a veces es denominado como ‘confusión de metaclase’, y se evita " "sobrepasando la instancia al buscar métodos especiales::" #: ../Doc/reference/datamodel.rst:3069 msgid "" "In addition to bypassing any instance attributes in the interest of " "correctness, implicit special method lookup generally also bypasses the :" "meth:`~object.__getattribute__` method even of the object's metaclass::" msgstr "" "Además de omitir cualquier atributo de instancia en aras de la corrección, " "la búsqueda implícita de métodos especiales generalmente también omite el " "método :meth:`~object.__getattribute__` incluso de la metaclase del objeto::" #: ../Doc/reference/datamodel.rst:3095 msgid "" "Bypassing the :meth:`~object.__getattribute__` machinery in this fashion " "provides significant scope for speed optimisations within the interpreter, " "at the cost of some flexibility in the handling of special methods (the " "special method *must* be set on the class object itself in order to be " "consistently invoked by the interpreter)." msgstr "" "Omitir la maquinaria :meth:`~object.__getattribute__` de esta manera " "proporciona un margen significativo para optimizar la velocidad dentro del " "intérprete, a costa de cierta flexibilidad en el manejo de métodos " "especiales (el método especial *must* debe configurarse en el propio objeto " "de clase para que el intérprete lo invoque consistentemente). )." #: ../Doc/reference/datamodel.rst:3106 msgid "Coroutines" msgstr "Corrutinas" #: ../Doc/reference/datamodel.rst:3110 msgid "Awaitable Objects" msgstr "Objetos esperables" #: ../Doc/reference/datamodel.rst:3112 msgid "" "An :term:`awaitable` object generally implements an :meth:`~object." "__await__` method. :term:`Coroutine objects ` returned from :" "keyword:`async def` functions are awaitable." msgstr "" "Un objeto :term:`awaitable` generalmente implementa un método :meth:`~object." "__await__`. :term:`Coroutine objects ` retornado por las " "funciones :keyword:`async def` están a la espera." #: ../Doc/reference/datamodel.rst:3118 msgid "" "The :term:`generator iterator` objects returned from generators decorated " "with :func:`types.coroutine` are also awaitable, but they do not implement :" "meth:`~object.__await__`." msgstr "" "Los objetos :term:`generator iterator` retornados por generadores decorados " "con :func:`types.coroutine` también están a la espera, pero no implementan :" "meth:`~object.__await__`." #: ../Doc/reference/datamodel.rst:3124 msgid "" "Must return an :term:`iterator`. Should be used to implement :term:" "`awaitable` objects. For instance, :class:`asyncio.Future` implements this " "method to be compatible with the :keyword:`await` expression." msgstr "" "Debe retornar un :term:`iterator`. Debe ser utilizado para implementar " "objetos :term:`awaitable`. Por ejemplo, :class:`asyncio.Future` implementa " "este método para ser compatible con la expresión :keyword:`await`." #: ../Doc/reference/datamodel.rst:3130 msgid "" "The language doesn't place any restriction on the type or value of the " "objects yielded by the iterator returned by ``__await__``, as this is " "specific to the implementation of the asynchronous execution framework (e." "g. :mod:`asyncio`) that will be managing the :term:`awaitable` object." msgstr "" "El lenguaje no impone ninguna restricción sobre el tipo o valor de los " "objetos generados por el iterador retornado por ``__await__``, ya que esto " "es específico de la implementación del marco de ejecución asincrónica (por " "ejemplo, :mod:`asyncio`) que administrará el objeto :term:`awaitable`." #: ../Doc/reference/datamodel.rst:3138 msgid ":pep:`492` for additional information about awaitable objects." msgstr ":pep:`492` para información adicional sobre objetos esperables." #: ../Doc/reference/datamodel.rst:3144 msgid "Coroutine Objects" msgstr "Objetos de corrutina" #: ../Doc/reference/datamodel.rst:3146 msgid "" ":term:`Coroutine objects ` are :term:`awaitable` objects. A " "coroutine's execution can be controlled by calling :meth:`~object.__await__` " "and iterating over the result. When the coroutine has finished executing " "and returns, the iterator raises :exc:`StopIteration`, and the exception's :" "attr:`~StopIteration.value` attribute holds the return value. If the " "coroutine raises an exception, it is propagated by the iterator. Coroutines " "should not directly raise unhandled :exc:`StopIteration` exceptions." msgstr "" ":term:`Coroutine objects ` son objetos :term:`awaitable`. La " "ejecución de una corrutina se puede controlar llamando a :meth:`~object." "__await__` e iterando sobre el resultado. Cuando la rutina termina de " "ejecutarse y regresa, el iterador genera :exc:`StopIteration` y el atributo :" "attr:`~StopIteration.value` de la excepción contiene el valor de retorno. Si " "la rutina genera una excepción, el iterador la propaga. Las corrutinas no " "deberían generar directamente excepciones :exc:`StopIteration` no " "controladas." #: ../Doc/reference/datamodel.rst:3154 msgid "" "Coroutines also have the methods listed below, which are analogous to those " "of generators (see :ref:`generator-methods`). However, unlike generators, " "coroutines do not directly support iteration." msgstr "" "Las corrutinas también tienen los métodos mencionados a continuación, los " "cuales son análogos a los de los generadores. (ver :ref:`generator-" "methods`). Sin embargo, a diferencia de los generadores, las corrutinas no " "soportan directamente iteración." #: ../Doc/reference/datamodel.rst:3158 msgid "It is a :exc:`RuntimeError` to await on a coroutine more than once." msgstr "" "Es un error :exc:`RuntimeError` esperar a una corrutina más de una vez." #: ../Doc/reference/datamodel.rst:3164 msgid "" "Starts or resumes execution of the coroutine. If *value* is ``None``, this " "is equivalent to advancing the iterator returned by :meth:`~object." "__await__`. If *value* is not ``None``, this method delegates to the :meth:" "`~generator.send` method of the iterator that caused the coroutine to " "suspend. The result (return value, :exc:`StopIteration`, or other " "exception) is the same as when iterating over the :meth:`__await__` return " "value, described above." msgstr "" "Inicia o reanuda la ejecución de la corrutina. Si *value* es ``None``, esto " "equivale a avanzar el iterador retornado por :meth:`~object.__await__`. Si " "*value* no es ``None``, este método delega en el método :meth:`~generator." "send` del iterador que provocó la suspensión de la rutina. El resultado " "(valor de retorno, :exc:`StopIteration` u otra excepción) es el mismo que " "cuando se itera sobre el valor de retorno :meth:`__await__`, descrito " "anteriormente." #: ../Doc/reference/datamodel.rst:3175 msgid "" "Raises the specified exception in the coroutine. This method delegates to " "the :meth:`~generator.throw` method of the iterator that caused the " "coroutine to suspend, if it has such a method. Otherwise, the exception is " "raised at the suspension point. The result (return value, :exc:" "`StopIteration`, or other exception) is the same as when iterating over the :" "meth:`~object.__await__` return value, described above. If the exception is " "not caught in the coroutine, it propagates back to the caller." msgstr "" "Genera la excepción especificada en la corrutina. Este método delega al " "método :meth:`~generator.throw` del iterador que provocó la suspensión de la " "rutina, si tiene dicho método. En caso contrario, la excepción se plantea en " "el punto de suspensión. El resultado (valor de retorno, :exc:`StopIteration` " "u otra excepción) es el mismo que cuando se itera sobre el valor de retorno :" "meth:`~object.__await__`, descrito anteriormente. Si la excepción no queda " "atrapada en la rutina, se propaga de nuevo a la persona que llama." #: ../Doc/reference/datamodel.rst:3186 msgid "" "The second signature \\(type\\[, value\\[, traceback\\]\\]\\) is deprecated " "and may be removed in a future version of Python." msgstr "" "La segunda firma \\(type\\[, value\\[, traceback\\]\\]\\) está obsoleta y " "puede eliminarse en una versión futura de Python." #: ../Doc/reference/datamodel.rst:3191 msgid "" "Causes the coroutine to clean itself up and exit. If the coroutine is " "suspended, this method first delegates to the :meth:`~generator.close` " "method of the iterator that caused the coroutine to suspend, if it has such " "a method. Then it raises :exc:`GeneratorExit` at the suspension point, " "causing the coroutine to immediately clean itself up. Finally, the coroutine " "is marked as having finished executing, even if it was never started." msgstr "" "Causa que la corrutina misma se borre a sí misma y termine su ejecución. Si " "la corrutina es suspendida, este método primero delega a :meth:`~generator." "close`, si existe, del iterador que causó la suspensión de la corrutina. " "Luego lanza una excepción :exc:`GeneratorExit` en el punto de suspensión, " "causando que la corrutina se borre a sí misma. Finalmente, la corrutina es " "marcada como completada, aún si nunca inició." #: ../Doc/reference/datamodel.rst:3199 msgid "" "Coroutine objects are automatically closed using the above process when they " "are about to be destroyed." msgstr "" "Objetos de corrutina son cerrados automáticamente utilizando el proceso " "anterior cuando están a punto de ser destruidos." #: ../Doc/reference/datamodel.rst:3205 msgid "Asynchronous Iterators" msgstr "Iteradores asíncronos" #: ../Doc/reference/datamodel.rst:3207 msgid "" "An *asynchronous iterator* can call asynchronous code in its ``__anext__`` " "method." msgstr "" "Un *iterador asíncrono* puede llamar código asíncrono en su método " "``__anext__``." #: ../Doc/reference/datamodel.rst:3210 msgid "" "Asynchronous iterators can be used in an :keyword:`async for` statement." msgstr "" "Iteradores asíncronos pueden ser utilizados en la declaración :keyword:" "`async for`." #: ../Doc/reference/datamodel.rst:3214 msgid "Must return an *asynchronous iterator* object." msgstr "Debe retornar un objeto de *iterador asíncrono*." #: ../Doc/reference/datamodel.rst:3218 msgid "" "Must return an *awaitable* resulting in a next value of the iterator. " "Should raise a :exc:`StopAsyncIteration` error when the iteration is over." msgstr "" "Debe retornar un *esperable* (awaitable) resultante en el siguiente valor " "del iterador. Debe levantar una excepción :exc:`StopAsyncIteration` cuando " "la iteración termina." #: ../Doc/reference/datamodel.rst:3221 msgid "An example of an asynchronous iterable object::" msgstr "Un ejemplo de objeto iterable asíncrono::" #: ../Doc/reference/datamodel.rst:3238 msgid "" "Prior to Python 3.7, :meth:`~object.__aiter__` could return an *awaitable* " "that would resolve to an :term:`asynchronous iterator `." msgstr "" "Antes de Python 3.7, :meth:`~object.__aiter__` podía retornar un *awaitable* " "que se resolvería en un :term:`asynchronous iterator `." #: ../Doc/reference/datamodel.rst:3243 msgid "" "Starting with Python 3.7, :meth:`~object.__aiter__` must return an " "asynchronous iterator object. Returning anything else will result in a :exc:" "`TypeError` error." msgstr "" "A partir de Python 3.7, :meth:`~object.__aiter__` debe retornar un objeto " "iterador asincrónico. Retornar cualquier otra cosa resultará en un error :" "exc:`TypeError`." #: ../Doc/reference/datamodel.rst:3251 msgid "Asynchronous Context Managers" msgstr "Gestores de contexto asíncronos" #: ../Doc/reference/datamodel.rst:3253 msgid "" "An *asynchronous context manager* is a *context manager* that is able to " "suspend execution in its ``__aenter__`` and ``__aexit__`` methods." msgstr "" "Un *gestor de contexto asíncrono* es un *gestor de contexto* que puede " "suspender la ejecución en sus métodos ``__aenter__`` y ``__aexit__``." #: ../Doc/reference/datamodel.rst:3256 msgid "" "Asynchronous context managers can be used in an :keyword:`async with` " "statement." msgstr "" "Los gestores de contexto asíncronos pueden ser utilizados en una " "declaración :keyword:`async with`." #: ../Doc/reference/datamodel.rst:3260 msgid "" "Semantically similar to :meth:`__enter__`, the only difference being that it " "must return an *awaitable*." msgstr "" "Semánticamente similar a :meth:`__enter__`, siendo la única diferencia que " "debe retorna un *esperable*." #: ../Doc/reference/datamodel.rst:3265 msgid "" "Semantically similar to :meth:`__exit__`, the only difference being that it " "must return an *awaitable*." msgstr "" "Semánticamente similar a :meth:`__exit__`, siendo la única diferencia que " "debe retornar un *esperable*." #: ../Doc/reference/datamodel.rst:3268 msgid "An example of an asynchronous context manager class::" msgstr "Un ejemplo de una clase de gestor de contexto asíncrono::" #: ../Doc/reference/datamodel.rst:3281 msgid "Footnotes" msgstr "Notas a pie de página" #: ../Doc/reference/datamodel.rst:3282 msgid "" "It *is* possible in some cases to change an object's type, under certain " "controlled conditions. It generally isn't a good idea though, since it can " "lead to some very strange behaviour if it is handled incorrectly." msgstr "" "Es posible cambiar en algunos casos un tipo de objeto bajo ciertas " "circunstancias controladas. Generalmente no es buena idea, ya que esto puede " "llevar a un comportamiento bastante extraño de no ser tratado correctamente." #: ../Doc/reference/datamodel.rst:3286 msgid "" "The :meth:`~object.__hash__`, :meth:`~object.__iter__`, :meth:`~object." "__reversed__`, and :meth:`~object.__contains__` methods have special " "handling for this; others will still raise a :exc:`TypeError`, but may do so " "by relying on the behavior that ``None`` is not callable." msgstr "" "Los métodos :meth:`~object.__hash__`, :meth:`~object.__iter__`, :meth:" "`~object.__reversed__` y :meth:`~object.__contains__` tienen un manejo " "especial para esto; otros seguirán generando un :exc:`TypeError`, pero " "pueden hacerlo confiando en el comportamiento de que ``None`` no es " "invocable." #: ../Doc/reference/datamodel.rst:3292 msgid "" "\"Does not support\" here means that the class has no such method, or the " "method returns ``NotImplemented``. Do not set the method to ``None`` if you " "want to force fallback to the right operand's reflected method—that will " "instead have the opposite effect of explicitly *blocking* such fallback." msgstr "" "“No soporta” aquí significa que la clase no tiene tal método, o el método " "retorna ``NotImplemented``. No establecer el método a ``None`` si se quiere " "forzar el retroceso al método reflejado del operando correcto—eso, por el " "contrario, tendrá un efecto opuesto de bloquear explícitamente dicho " "retroceso." #: ../Doc/reference/datamodel.rst:3298 msgid "" "For operands of the same type, it is assumed that if the non-reflected " "method -- such as :meth:`~object.__add__` -- fails then the overall " "operation is not supported, which is why the reflected method is not called." msgstr "" "Para operandos del mismo tipo, se supone que si el método no reflejado " "(como :meth:`~object.__add__`) falla, entonces la operación general no es " "compatible, razón por la cual no se llama al método reflejado." #: ../Doc/reference/datamodel.rst:14 ../Doc/reference/datamodel.rst:148 #: ../Doc/reference/datamodel.rst:159 ../Doc/reference/datamodel.rst:180 #: ../Doc/reference/datamodel.rst:192 ../Doc/reference/datamodel.rst:225 #: ../Doc/reference/datamodel.rst:246 ../Doc/reference/datamodel.rst:261 #: ../Doc/reference/datamodel.rst:279 ../Doc/reference/datamodel.rst:292 #: ../Doc/reference/datamodel.rst:321 ../Doc/reference/datamodel.rst:356 #: ../Doc/reference/datamodel.rst:381 ../Doc/reference/datamodel.rst:402 #: ../Doc/reference/datamodel.rst:420 ../Doc/reference/datamodel.rst:440 #: ../Doc/reference/datamodel.rst:448 ../Doc/reference/datamodel.rst:459 #: ../Doc/reference/datamodel.rst:476 ../Doc/reference/datamodel.rst:512 #: ../Doc/reference/datamodel.rst:525 ../Doc/reference/datamodel.rst:640 #: ../Doc/reference/datamodel.rst:760 ../Doc/reference/datamodel.rst:778 #: ../Doc/reference/datamodel.rst:810 ../Doc/reference/datamodel.rst:891 #: ../Doc/reference/datamodel.rst:959 ../Doc/reference/datamodel.rst:986 #: ../Doc/reference/datamodel.rst:1048 ../Doc/reference/datamodel.rst:1102 #: ../Doc/reference/datamodel.rst:1162 ../Doc/reference/datamodel.rst:1227 #: ../Doc/reference/datamodel.rst:1618 ../Doc/reference/datamodel.rst:2626 msgid "object" msgstr "Objetos" #: ../Doc/reference/datamodel.rst:14 ../Doc/reference/datamodel.rst:122 msgid "data" msgstr "datos" #: ../Doc/reference/datamodel.rst:23 ../Doc/reference/datamodel.rst:292 #: ../Doc/reference/datamodel.rst:336 ../Doc/reference/datamodel.rst:420 #: ../Doc/reference/datamodel.rst:459 ../Doc/reference/datamodel.rst:760 #: ../Doc/reference/datamodel.rst:1005 ../Doc/reference/datamodel.rst:1292 #: ../Doc/reference/datamodel.rst:1532 ../Doc/reference/datamodel.rst:1537 #: ../Doc/reference/datamodel.rst:1618 ../Doc/reference/datamodel.rst:2168 #: ../Doc/reference/datamodel.rst:2596 ../Doc/reference/datamodel.rst:2754 #: ../Doc/reference/datamodel.rst:2789 ../Doc/reference/datamodel.rst:2803 #: ../Doc/reference/datamodel.rst:2850 ../Doc/reference/datamodel.rst:2860 #: ../Doc/reference/datamodel.rst:2888 msgid "built-in function" msgstr "Funciones incorporadas" #: ../Doc/reference/datamodel.rst:23 msgid "id" msgstr "identificación" #: ../Doc/reference/datamodel.rst:23 ../Doc/reference/datamodel.rst:122 #: ../Doc/reference/datamodel.rst:2168 msgid "type" msgstr "Tipos" #: ../Doc/reference/datamodel.rst:23 msgid "identity of an object" msgstr "identidad de un objeto" #: ../Doc/reference/datamodel.rst:23 msgid "value of an object" msgstr "valor de un objeto" #: ../Doc/reference/datamodel.rst:23 msgid "type of an object" msgstr "Tipos de objeto" #: ../Doc/reference/datamodel.rst:23 msgid "mutable object" msgstr "Objetos mutables" #: ../Doc/reference/datamodel.rst:23 msgid "immutable object" msgstr "Objetos inmutables" #: ../Doc/reference/datamodel.rst:60 msgid "garbage collection" msgstr "recolección de basura" #: ../Doc/reference/datamodel.rst:60 msgid "reference counting" msgstr "conteo de referencias" #: ../Doc/reference/datamodel.rst:60 msgid "unreachable object" msgstr "objetos que no se pueden acceder" #: ../Doc/reference/datamodel.rst:95 ../Doc/reference/datamodel.rst:891 msgid "container" msgstr "contenedores" #: ../Doc/reference/datamodel.rst:122 msgid "hierarchy" msgstr "jerarquía" #: ../Doc/reference/datamodel.rst:122 msgid "extension" msgstr "extensión" #: ../Doc/reference/datamodel.rst:122 ../Doc/reference/datamodel.rst:393 #: ../Doc/reference/datamodel.rst:394 ../Doc/reference/datamodel.rst:495 #: ../Doc/reference/datamodel.rst:810 ../Doc/reference/datamodel.rst:829 #: ../Doc/reference/datamodel.rst:1005 msgid "module" msgstr "Módulo" #: ../Doc/reference/datamodel.rst:122 ../Doc/reference/datamodel.rst:261 #: ../Doc/reference/datamodel.rst:760 msgid "C" msgstr "C" #: ../Doc/reference/datamodel.rst:122 ../Doc/reference/datamodel.rst:261 #: ../Doc/reference/datamodel.rst:760 msgid "language" msgstr "lenguaje" #: ../Doc/reference/datamodel.rst:135 ../Doc/reference/datamodel.rst:891 #: ../Doc/reference/datamodel.rst:908 ../Doc/reference/datamodel.rst:959 #: ../Doc/reference/datamodel.rst:979 msgid "attribute" msgstr "atributo" #: ../Doc/reference/datamodel.rst:135 msgid "special" msgstr "especial" #: ../Doc/reference/datamodel.rst:135 msgid "generic" msgstr "genérico" #: ../Doc/reference/datamodel.rst:180 msgid "..." msgstr "..." #: ../Doc/reference/datamodel.rst:180 msgid "ellipsis literal" msgstr "elipsis literal" #: ../Doc/reference/datamodel.rst:192 ../Doc/reference/datamodel.rst:986 msgid "numeric" msgstr "numérico" #: ../Doc/reference/datamodel.rst:225 ../Doc/reference/datamodel.rst:231 #: ../Doc/reference/datamodel.rst:336 msgid "integer" msgstr "entero" #: ../Doc/reference/datamodel.rst:231 msgid "representation" msgstr "representación" #: ../Doc/reference/datamodel.rst:246 msgid "Boolean" msgstr "booleano" #: ../Doc/reference/datamodel.rst:246 msgid "False" msgstr "Falso" #: ../Doc/reference/datamodel.rst:246 msgid "True" msgstr "Verdad" #: ../Doc/reference/datamodel.rst:261 msgid "floating point" msgstr "punto flotante" #: ../Doc/reference/datamodel.rst:261 ../Doc/reference/datamodel.rst:279 msgid "number" msgstr "número" #: ../Doc/reference/datamodel.rst:261 msgid "Java" msgstr "Java" #: ../Doc/reference/datamodel.rst:279 ../Doc/reference/datamodel.rst:2860 msgid "complex" msgstr "complejo" #: ../Doc/reference/datamodel.rst:292 ../Doc/reference/datamodel.rst:420 #: ../Doc/reference/datamodel.rst:459 ../Doc/reference/datamodel.rst:2596 msgid "len" msgstr "len" #: ../Doc/reference/datamodel.rst:292 ../Doc/reference/datamodel.rst:986 msgid "sequence" msgstr "Secuencias" #: ../Doc/reference/datamodel.rst:292 msgid "index operation" msgstr "operación de índice" #: ../Doc/reference/datamodel.rst:292 msgid "item selection" msgstr "selección de artículos" #: ../Doc/reference/datamodel.rst:292 ../Doc/reference/datamodel.rst:381 #: ../Doc/reference/datamodel.rst:459 msgid "subscription" msgstr "suscripción" #: ../Doc/reference/datamodel.rst:304 ../Doc/reference/datamodel.rst:381 msgid "slicing" msgstr "rebanar" #: ../Doc/reference/datamodel.rst:321 msgid "immutable sequence" msgstr "Secuencia inmutable" #: ../Doc/reference/datamodel.rst:321 msgid "immutable" msgstr "inmutable" #: ../Doc/reference/datamodel.rst:332 ../Doc/reference/datamodel.rst:1507 #: ../Doc/reference/datamodel.rst:1537 msgid "string" msgstr "cadenas de caracteres" #: ../Doc/reference/datamodel.rst:332 msgid "immutable sequences" msgstr "secuencias inmutables" #: ../Doc/reference/datamodel.rst:336 msgid "chr" msgstr "chr" #: ../Doc/reference/datamodel.rst:336 msgid "ord" msgstr "ord" #: ../Doc/reference/datamodel.rst:336 msgid "character" msgstr "caracter" #: ../Doc/reference/datamodel.rst:336 msgid "Unicode" msgstr "Unicode" #: ../Doc/reference/datamodel.rst:356 msgid "tuple" msgstr "tupla" #: ../Doc/reference/datamodel.rst:356 msgid "singleton" msgstr "único" #: ../Doc/reference/datamodel.rst:356 msgid "empty" msgstr "vacío" #: ../Doc/reference/datamodel.rst:369 ../Doc/reference/datamodel.rst:1532 msgid "bytes" msgstr "bytes" #: ../Doc/reference/datamodel.rst:369 msgid "byte" msgstr "byte" #: ../Doc/reference/datamodel.rst:381 msgid "mutable sequence" msgstr "secuencia mutable" #: ../Doc/reference/datamodel.rst:381 msgid "mutable" msgstr "mutable" #: ../Doc/reference/datamodel.rst:381 ../Doc/reference/datamodel.rst:908 #: ../Doc/reference/datamodel.rst:979 msgid "assignment" msgstr "asignación" #: ../Doc/reference/datamodel.rst:381 ../Doc/reference/datamodel.rst:810 #: ../Doc/reference/datamodel.rst:1259 ../Doc/reference/datamodel.rst:1428 #: ../Doc/reference/datamodel.rst:2915 msgid "statement" msgstr "declaración" #: ../Doc/reference/datamodel.rst:393 msgid "array" msgstr "arreglo" #: ../Doc/reference/datamodel.rst:394 msgid "collections" msgstr "colecciones" #: ../Doc/reference/datamodel.rst:402 msgid "list" msgstr "lista" #: ../Doc/reference/datamodel.rst:409 msgid "bytearray" msgstr "arreglo de bytes" #: ../Doc/reference/datamodel.rst:420 msgid "set type" msgstr "tipo conjunto" #: ../Doc/reference/datamodel.rst:440 msgid "set" msgstr "conjunto" #: ../Doc/reference/datamodel.rst:448 msgid "frozenset" msgstr "conjunto congelado" #: ../Doc/reference/datamodel.rst:459 ../Doc/reference/datamodel.rst:986 msgid "mapping" msgstr "mapeos" #: ../Doc/reference/datamodel.rst:476 ../Doc/reference/datamodel.rst:891 #: ../Doc/reference/datamodel.rst:1618 msgid "dictionary" msgstr "diccionario" #: ../Doc/reference/datamodel.rst:495 msgid "dbm.ndbm" msgstr "dbm.ndbm" #: ../Doc/reference/datamodel.rst:495 msgid "dbm.gnu" msgstr "dbm.gnu" #: ../Doc/reference/datamodel.rst:512 msgid "callable" msgstr "invocable" #: ../Doc/reference/datamodel.rst:512 ../Doc/reference/datamodel.rst:525 #: ../Doc/reference/datamodel.rst:706 ../Doc/reference/datamodel.rst:724 #: ../Doc/reference/datamodel.rst:737 ../Doc/reference/datamodel.rst:760 msgid "function" msgstr "función" #: ../Doc/reference/datamodel.rst:512 ../Doc/reference/datamodel.rst:891 #: ../Doc/reference/datamodel.rst:913 ../Doc/reference/datamodel.rst:2549 msgid "call" msgstr "llamada" #: ../Doc/reference/datamodel.rst:512 msgid "invocation" msgstr "invocación" #: ../Doc/reference/datamodel.rst:512 msgid "argument" msgstr "argumento" #: ../Doc/reference/datamodel.rst:525 ../Doc/reference/datamodel.rst:640 msgid "user-defined" msgstr "definida por el usuario" #: ../Doc/reference/datamodel.rst:525 msgid "user-defined function" msgstr "función definida por el usuario" #: ../Doc/reference/datamodel.rst:539 msgid "__doc__ (function attribute)" msgstr "__doc__ (atributo función)" #: ../Doc/reference/datamodel.rst:539 msgid "__name__ (function attribute)" msgstr "__name__ (atributo función)" #: ../Doc/reference/datamodel.rst:539 msgid "__module__ (function attribute)" msgstr "__module__ (atributo función)" #: ../Doc/reference/datamodel.rst:539 msgid "__dict__ (function attribute)" msgstr "__dict__ (atributo función)" #: ../Doc/reference/datamodel.rst:539 msgid "__defaults__ (function attribute)" msgstr "__defaults__ (atributo función)" #: ../Doc/reference/datamodel.rst:539 msgid "__closure__ (function attribute)" msgstr "__closure__ (atributo función)" #: ../Doc/reference/datamodel.rst:539 msgid "__code__ (function attribute)" msgstr "__code__ (atributo función)" #: ../Doc/reference/datamodel.rst:539 msgid "__globals__ (function attribute)" msgstr "__globals__ (atributo función)" #: ../Doc/reference/datamodel.rst:539 msgid "__annotations__ (function attribute)" msgstr "__annotations__ (atributo función)" #: ../Doc/reference/datamodel.rst:539 msgid "__kwdefaults__ (function attribute)" msgstr "__kwdefaults__ (atributo función)" #: ../Doc/reference/datamodel.rst:539 msgid "__type_params__ (function attribute)" msgstr "__type_params__ (atributo función)" #: ../Doc/reference/datamodel.rst:539 msgid "global" msgstr "global" #: ../Doc/reference/datamodel.rst:539 ../Doc/reference/datamodel.rst:829 msgid "namespace" msgstr "espacio de nombre" #: ../Doc/reference/datamodel.rst:640 ../Doc/reference/datamodel.rst:778 msgid "method" msgstr "método" #: ../Doc/reference/datamodel.rst:640 msgid "user-defined method" msgstr "método definido por el usuario" #: ../Doc/reference/datamodel.rst:648 msgid "__func__ (method attribute)" msgstr "__func__ (atributo método)" #: ../Doc/reference/datamodel.rst:648 msgid "__self__ (method attribute)" msgstr "__self__ (atributo método)" #: ../Doc/reference/datamodel.rst:648 msgid "__doc__ (method attribute)" msgstr "__doc__ (atributo método)" #: ../Doc/reference/datamodel.rst:648 msgid "__name__ (method attribute)" msgstr "__name__ (atributo método)" #: ../Doc/reference/datamodel.rst:648 msgid "__module__ (method attribute)" msgstr "__module__ (atributo método)" #: ../Doc/reference/datamodel.rst:706 ../Doc/reference/datamodel.rst:1102 msgid "generator" msgstr "generador" #: ../Doc/reference/datamodel.rst:706 msgid "iterator" msgstr "iterador" #: ../Doc/reference/datamodel.rst:724 ../Doc/reference/datamodel.rst:3102 msgid "coroutine" msgstr "corrutina" #: ../Doc/reference/datamodel.rst:737 msgid "asynchronous generator" msgstr "generador asíncrono" #: ../Doc/reference/datamodel.rst:737 msgid "asynchronous iterator" msgstr "iterador asíncrono" #: ../Doc/reference/datamodel.rst:778 msgid "built-in method" msgstr "método incorporado" #: ../Doc/reference/datamodel.rst:778 msgid "built-in" msgstr "incorporado" #: ../Doc/reference/datamodel.rst:810 msgid "import" msgstr "importar" #: ../Doc/reference/datamodel.rst:829 msgid "__name__ (module attribute)" msgstr "__name__ (atributo módulo)" #: ../Doc/reference/datamodel.rst:829 msgid "__doc__ (module attribute)" msgstr "__doc__ (atributo módulo)" #: ../Doc/reference/datamodel.rst:829 msgid "__file__ (module attribute)" msgstr "__file__ (atributo módulo)" #: ../Doc/reference/datamodel.rst:829 msgid "__annotations__ (module attribute)" msgstr "__annotations__ (atributo módulo)" #: ../Doc/reference/datamodel.rst:860 msgid "__dict__ (module attribute)" msgstr "__dict__ (atributo módulo)" #: ../Doc/reference/datamodel.rst:891 ../Doc/reference/datamodel.rst:908 #: ../Doc/reference/datamodel.rst:959 ../Doc/reference/datamodel.rst:1411 #: ../Doc/reference/datamodel.rst:2279 msgid "class" msgstr "clase" #: ../Doc/reference/datamodel.rst:891 ../Doc/reference/datamodel.rst:959 #: ../Doc/reference/datamodel.rst:979 msgid "class instance" msgstr "instancia de clase" #: ../Doc/reference/datamodel.rst:891 ../Doc/reference/datamodel.rst:959 #: ../Doc/reference/datamodel.rst:2549 msgid "instance" msgstr "instancia" #: ../Doc/reference/datamodel.rst:891 ../Doc/reference/datamodel.rst:913 msgid "class object" msgstr "objeto de clase" #: ../Doc/reference/datamodel.rst:917 msgid "__name__ (class attribute)" msgstr "__name__ (atributo de clase)" #: ../Doc/reference/datamodel.rst:917 msgid "__module__ (class attribute)" msgstr "__module__ (atributo de clase)" #: ../Doc/reference/datamodel.rst:917 msgid "__dict__ (class attribute)" msgstr "__dict__ (atributo de clase)" #: ../Doc/reference/datamodel.rst:917 msgid "__bases__ (class attribute)" msgstr "__bases__ (atributo de clase)" #: ../Doc/reference/datamodel.rst:917 msgid "__doc__ (class attribute)" msgstr "__doc__ (atributo de clase)" #: ../Doc/reference/datamodel.rst:917 msgid "__annotations__ (class attribute)" msgstr "__annotations__ (atributo de clase)" #: ../Doc/reference/datamodel.rst:917 msgid "__type_params__ (class attribute)" msgstr "__type_params__ (atributo de clase)" #: ../Doc/reference/datamodel.rst:994 msgid "__dict__ (instance attribute)" msgstr "__dict__ (atributo de instancia)" #: ../Doc/reference/datamodel.rst:994 msgid "__class__ (instance attribute)" msgstr "__class__ (atributo de instancia)" #: ../Doc/reference/datamodel.rst:1005 msgid "open" msgstr "abrir" #: ../Doc/reference/datamodel.rst:1005 msgid "io" msgstr "io" #: ../Doc/reference/datamodel.rst:1005 msgid "popen() (in module os)" msgstr "popen() (en el módulo os)" #: ../Doc/reference/datamodel.rst:1005 msgid "makefile() (socket method)" msgstr "makefile() (método de socket)" #: ../Doc/reference/datamodel.rst:1005 msgid "sys.stdin" msgstr "sys.stdin" #: ../Doc/reference/datamodel.rst:1005 msgid "sys.stdout" msgstr "sys.stdout" #: ../Doc/reference/datamodel.rst:1005 msgid "sys.stderr" msgstr "sys.stderr" #: ../Doc/reference/datamodel.rst:1005 msgid "stdio" msgstr "stdio" #: ../Doc/reference/datamodel.rst:1005 msgid "stdin (in module sys)" msgstr "stdin (en el módulo sys)" #: ../Doc/reference/datamodel.rst:1005 msgid "stdout (in module sys)" msgstr "stdout (en el módulo sys)" #: ../Doc/reference/datamodel.rst:1005 msgid "stderr (in module sys)" msgstr "stderr (en el módulo sys)" #: ../Doc/reference/datamodel.rst:1034 msgid "internal type" msgstr "tipo interno" #: ../Doc/reference/datamodel.rst:1034 msgid "types, internal" msgstr "tipos, interno" #: ../Doc/reference/datamodel.rst:1048 msgid "bytecode" msgstr "bytecode" #: ../Doc/reference/datamodel.rst:1048 msgid "code" msgstr "code" #: ../Doc/reference/datamodel.rst:1048 msgid "code object" msgstr "objeto de código" #: ../Doc/reference/datamodel.rst:1059 msgid "co_argcount (code object attribute)" msgstr "co_argcount (atributo de objeto de código)" #: ../Doc/reference/datamodel.rst:1059 msgid "co_posonlyargcount (code object attribute)" msgstr "co_posonlyargcount (atributo de objeto de código)" #: ../Doc/reference/datamodel.rst:1059 msgid "co_kwonlyargcount (code object attribute)" msgstr "co_kwonlyargcount (atributo de objeto de código)" #: ../Doc/reference/datamodel.rst:1059 msgid "co_code (code object attribute)" msgstr "co_code (atributo de objeto de código)" #: ../Doc/reference/datamodel.rst:1059 msgid "co_consts (code object attribute)" msgstr "co_consts (atributo de objeto de código)" #: ../Doc/reference/datamodel.rst:1059 msgid "co_filename (code object attribute)" msgstr "co_filename (atributo de objeto de código)" #: ../Doc/reference/datamodel.rst:1059 msgid "co_firstlineno (code object attribute)" msgstr "co_firstlineno (atributo de objeto de código)" #: ../Doc/reference/datamodel.rst:1059 msgid "co_flags (code object attribute)" msgstr "co_flags (atributo de objeto de código)" #: ../Doc/reference/datamodel.rst:1059 msgid "co_lnotab (code object attribute)" msgstr "co_lnotab (atributo de objeto de código)" #: ../Doc/reference/datamodel.rst:1059 msgid "co_name (code object attribute)" msgstr "co_name (atributo de objeto de código)" #: ../Doc/reference/datamodel.rst:1059 msgid "co_names (code object attribute)" msgstr "co_names (atributo de objeto de código)" #: ../Doc/reference/datamodel.rst:1059 msgid "co_nlocals (code object attribute)" msgstr "co_nlocals (atributo de objeto de código)" #: ../Doc/reference/datamodel.rst:1059 msgid "co_stacksize (code object attribute)" msgstr "co_stacksize (atributo de objeto de código)" #: ../Doc/reference/datamodel.rst:1059 msgid "co_varnames (code object attribute)" msgstr "co_varnames (atributo de objeto de código)" #: ../Doc/reference/datamodel.rst:1059 msgid "co_cellvars (code object attribute)" msgstr "co_cellvars (atributo de objeto de código)" #: ../Doc/reference/datamodel.rst:1059 msgid "co_freevars (code object attribute)" msgstr "co_freevars (atributo de objeto de código)" #: ../Doc/reference/datamodel.rst:1059 msgid "co_qualname (code object attribute)" msgstr "co_qualname (atributo de objeto de código)" #: ../Doc/reference/datamodel.rst:1118 msgid "documentation string" msgstr "cadena de caracteres de documentación" #: ../Doc/reference/datamodel.rst:1162 msgid "frame" msgstr "frame" #: ../Doc/reference/datamodel.rst:1167 msgid "f_back (frame attribute)" msgstr "f_back (atributo de frame)" #: ../Doc/reference/datamodel.rst:1167 msgid "f_code (frame attribute)" msgstr "f_code (atributo de frame)" #: ../Doc/reference/datamodel.rst:1167 msgid "f_globals (frame attribute)" msgstr "f_globals (atributo de frame)" #: ../Doc/reference/datamodel.rst:1167 msgid "f_locals (frame attribute)" msgstr "f_locals (atributo de frame)" #: ../Doc/reference/datamodel.rst:1167 msgid "f_lasti (frame attribute)" msgstr "f_lasti (atributo de frame)" #: ../Doc/reference/datamodel.rst:1167 msgid "f_builtins (frame attribute)" msgstr "f_builtins (atributo de frame)" #: ../Doc/reference/datamodel.rst:1186 msgid "f_trace (frame attribute)" msgstr "f_trace (atributo de frame)" #: ../Doc/reference/datamodel.rst:1186 msgid "f_trace_lines (frame attribute)" msgstr "f_trace_lines (atributo de frame)" #: ../Doc/reference/datamodel.rst:1186 msgid "f_trace_opcodes (frame attribute)" msgstr "f_trace_opcodes (atributo de frame)" #: ../Doc/reference/datamodel.rst:1186 msgid "f_lineno (frame attribute)" msgstr "f_lineno (atributo de frame)" #: ../Doc/reference/datamodel.rst:1227 msgid "traceback" msgstr "traceback" #: ../Doc/reference/datamodel.rst:1227 msgid "stack" msgstr "stack" #: ../Doc/reference/datamodel.rst:1227 msgid "trace" msgstr "trace" #: ../Doc/reference/datamodel.rst:1227 msgid "exception" msgstr "excepción" #: ../Doc/reference/datamodel.rst:1227 msgid "handler" msgstr "manejador" #: ../Doc/reference/datamodel.rst:1227 msgid "execution" msgstr "execution" #: ../Doc/reference/datamodel.rst:1227 msgid "exc_info (in module sys)" msgstr "exc_info (en el módulo sys)" #: ../Doc/reference/datamodel.rst:1227 msgid "last_traceback (in module sys)" msgstr "last_traceback (en el módulo sys)" #: ../Doc/reference/datamodel.rst:1227 msgid "sys.exc_info" msgstr "sys.exc_info" #: ../Doc/reference/datamodel.rst:1227 msgid "sys.exception" msgstr "sys.exception" #: ../Doc/reference/datamodel.rst:1227 msgid "sys.last_traceback" msgstr "sys.last_traceback" #: ../Doc/reference/datamodel.rst:1259 msgid "tb_frame (traceback attribute)" msgstr "tb_frame (atributo de traceback)" #: ../Doc/reference/datamodel.rst:1259 msgid "tb_lineno (traceback attribute)" msgstr "tb_lineno (atributo de traceback)" #: ../Doc/reference/datamodel.rst:1259 msgid "tb_lasti (traceback attribute)" msgstr "tb_lasti (atributo de traceback)" #: ../Doc/reference/datamodel.rst:1259 msgid "try" msgstr "try" #: ../Doc/reference/datamodel.rst:1277 msgid "tb_next (traceback attribute)" msgstr "tb_next (atributo de traceback)" #: ../Doc/reference/datamodel.rst:1292 ../Doc/reference/datamodel.rst:2626 msgid "slice" msgstr "slice" #: ../Doc/reference/datamodel.rst:1298 msgid "start (slice object attribute)" msgstr "comienzo (atributo de objeto slice)" #: ../Doc/reference/datamodel.rst:1298 msgid "stop (slice object attribute)" msgstr "stop (atributo de objeto slice)" #: ../Doc/reference/datamodel.rst:1298 msgid "step (slice object attribute)" msgstr "step (atributo de objeto slice)" #: ../Doc/reference/datamodel.rst:1346 msgid "operator" msgstr "operador" #: ../Doc/reference/datamodel.rst:1346 msgid "overloading" msgstr "sobrecarga" #: ../Doc/reference/datamodel.rst:1346 msgid "__getitem__() (mapping object method)" msgstr "__getitem__() (método de objeto mapping)" #: ../Doc/reference/datamodel.rst:1382 msgid "subclassing" msgstr "subclase" #: ../Doc/reference/datamodel.rst:1382 msgid "immutable types" msgstr "tipos inmutables" #: ../Doc/reference/datamodel.rst:1411 msgid "constructor" msgstr "constructor" #: ../Doc/reference/datamodel.rst:1428 msgid "destructor" msgstr "destructor" #: ../Doc/reference/datamodel.rst:1428 msgid "finalizer" msgstr "finalizador" #: ../Doc/reference/datamodel.rst:1428 msgid "del" msgstr "del" #: ../Doc/reference/datamodel.rst:1490 msgid "repr() (built-in function)" msgstr "repr() (función incorporada)" #: ../Doc/reference/datamodel.rst:1490 msgid "__repr__() (object method)" msgstr "__repr__() (método objeto)" #: ../Doc/reference/datamodel.rst:1507 msgid "__str__() (object method)" msgstr "__str__() (método objeto)" #: ../Doc/reference/datamodel.rst:1507 msgid "format() (built-in function)" msgstr "format() (función incorporada)" #: ../Doc/reference/datamodel.rst:1507 msgid "print() (built-in function)" msgstr "print() (función incorporada)" #: ../Doc/reference/datamodel.rst:1537 msgid "__format__() (object method)" msgstr "__format__() (método objeto)" #: ../Doc/reference/datamodel.rst:1537 msgid "conversion" msgstr "conversión" #: ../Doc/reference/datamodel.rst:1537 msgid "print" msgstr "print" #: ../Doc/reference/datamodel.rst:1576 msgid "comparisons" msgstr "comparaciones" #: ../Doc/reference/datamodel.rst:1618 msgid "hash" msgstr "hash" #: ../Doc/reference/datamodel.rst:1699 msgid "__len__() (mapping object method)" msgstr "__len__() (método objeto mapping)" #: ../Doc/reference/datamodel.rst:1802 msgid "__getattr__ (module attribute)" msgstr "__getattr__ (atributo de módulo)" #: ../Doc/reference/datamodel.rst:1802 msgid "__dir__ (module attribute)" msgstr "__dir__ (atributo de módulo)" #: ../Doc/reference/datamodel.rst:1802 msgid "__class__ (module attribute)" msgstr "__class__ (atributo de módulo)" #: ../Doc/reference/datamodel.rst:2168 msgid "metaclass" msgstr "metaclases" #: ../Doc/reference/datamodel.rst:2168 msgid "= (equals)" msgstr "= (es igual a)" #: ../Doc/reference/datamodel.rst:2168 msgid "class definition" msgstr "definición de clase" #: ../Doc/reference/datamodel.rst:2232 msgid "metaclass hint" msgstr "pista de metaclase" #: ../Doc/reference/datamodel.rst:2255 msgid "__prepare__ (metaclass method)" msgstr "__prepare__ (método de metaclase)" #: ../Doc/reference/datamodel.rst:2279 msgid "body" msgstr "cuerpo" #: ../Doc/reference/datamodel.rst:2299 msgid "__class__ (method cell)" msgstr "__class__ (celda de método)" #: ../Doc/reference/datamodel.rst:2299 msgid "__classcell__ (class namespace entry)" msgstr "__classcell;__ (entrada de espacio de nombre de clase)" #: ../Doc/reference/datamodel.rst:2596 msgid "__bool__() (object method)" msgstr "__bool__() (método objeto)" #: ../Doc/reference/datamodel.rst:2754 ../Doc/reference/datamodel.rst:2789 msgid "divmod" msgstr "divmod" #: ../Doc/reference/datamodel.rst:2754 ../Doc/reference/datamodel.rst:2789 #: ../Doc/reference/datamodel.rst:2803 msgid "pow" msgstr "pow" #: ../Doc/reference/datamodel.rst:2850 msgid "abs" msgstr "abs" #: ../Doc/reference/datamodel.rst:2860 msgid "int" msgstr "int" #: ../Doc/reference/datamodel.rst:2860 msgid "float" msgstr "float" #: ../Doc/reference/datamodel.rst:2888 msgid "round" msgstr "round" #: ../Doc/reference/datamodel.rst:2915 msgid "with" msgstr "with" #: ../Doc/reference/datamodel.rst:2915 msgid "context manager" msgstr "gestor de contexto"