# 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: 2022-10-25 19:47+0200\n" "PO-Revision-Date: 2021-12-09 23:44-0300\n" "Last-Translator: Cristián Maureira-Fredes \n" "Language: es\n" "Language-Team: python-doc-es\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" "Generated-By: Babel 2.10.3\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:150 msgid "None" msgstr "None" #: ../Doc/reference/datamodel.rst:147 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:170 msgid "NotImplemented" msgstr "NotImplemented" #: ../Doc/reference/datamodel.rst:155 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 devolver 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:162 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:166 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 msgid "Ellipsis" msgstr "Elipsis" #: ../Doc/reference/datamodel.rst:177 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:266 msgid ":class:`numbers.Number`" msgstr ":class:`numbers.Number`" #: ../Doc/reference/datamodel.rst:184 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:190 #, fuzzy 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 las clases numéricas, calculadas por :meth:" "`__repr__` y :meth:`__str__`, tienen las siguientes propiedades:" #: ../Doc/reference/datamodel.rst:194 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:198 msgid "The representation is in base 10, when possible." msgstr "La representación está en base 10, cuando sea posible." #: ../Doc/reference/datamodel.rst:200 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:203 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:206 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:208 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:241 msgid ":class:`numbers.Integral`" msgstr ":class:`numbers.Integral`" #: ../Doc/reference/datamodel.rst:214 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:217 msgid "There are two types of integers:" msgstr "Hay dos tipos de números enteros:" #: ../Doc/reference/datamodel.rst:224 msgid "Integers (:class:`int`)" msgstr "Enteros (:class:`int`)" #: ../Doc/reference/datamodel.rst:220 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:236 msgid "Booleans (:class:`bool`)" msgstr "Booleanos (:class:`bool`)" #: ../Doc/reference/datamodel.rst:232 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:240 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:256 msgid ":class:`numbers.Real` (:class:`float`)" msgstr ":class:`numbers.Real` (:class:`float`)" #: ../Doc/reference/datamodel.rst:250 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:266 msgid ":class:`numbers.Complex` (:class:`complex`)" msgstr ":class:`numbers.Complex` (:class:`complex`)" #: ../Doc/reference/datamodel.rst:263 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:383 msgid "Sequences" msgstr "Secuencias" #: ../Doc/reference/datamodel.rst:276 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:283 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:288 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:292 msgid "Sequences are distinguished according to their mutability:" msgstr "Las secuencias se distinguen según su mutabilidad:" #: ../Doc/reference/datamodel.rst:349 msgid "Immutable sequences" msgstr "Secuencias inmutables" #: ../Doc/reference/datamodel.rst:299 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:304 msgid "The following types are immutable sequences:" msgstr "Los siguientes tipos son secuencias inmutables:" #: ../Doc/reference/datamodel.rst:327 msgid "Strings" msgstr "Cadenas de caracteres" #: ../Doc/reference/datamodel.rst:317 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 "" #: ../Doc/reference/datamodel.rst:340 msgid "Tuples" msgstr "Tuplas" #: ../Doc/reference/datamodel.rst:335 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:349 msgid "Bytes" msgstr "Bytes" #: ../Doc/reference/datamodel.rst:345 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:383 msgid "Mutable sequences" msgstr "Secuencias mutables" #: ../Doc/reference/datamodel.rst:359 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:363 msgid "There are currently two intrinsic mutable sequence types:" msgstr "Actualmente hay dos tipos intrínsecos de secuencias mutable:" #: ../Doc/reference/datamodel.rst:370 msgid "Lists" msgstr "Listas" #: ../Doc/reference/datamodel.rst:368 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:378 msgid "Byte Arrays" msgstr "Colecciones de bytes" #: ../Doc/reference/datamodel.rst:375 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:382 msgid "" "The extension module :mod:`array` provides an additional example of a " "mutable sequence type, as does the :mod:`collections` module." msgstr "" "El módulo de extensión :mod:`array` proporciona un ejemplo adicional de un " "tipo de secuencia mutable, al igual que el módulo :mod:`collections`." #: ../Doc/reference/datamodel.rst:417 msgid "Set types" msgstr "Tipos de conjuntos" #: ../Doc/reference/datamodel.rst:390 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:397 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:402 msgid "There are currently two intrinsic set types:" msgstr "Actualmente hay dos tipos de conjuntos intrínsecos:" #: ../Doc/reference/datamodel.rst:409 msgid "Sets" msgstr "Conjuntos" #: ../Doc/reference/datamodel.rst:407 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:417 msgid "Frozen sets" msgstr "Conjuntos congelados" #: ../Doc/reference/datamodel.rst:414 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:464 msgid "Mappings" msgstr "Mapeos" #: ../Doc/reference/datamodel.rst:425 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:431 msgid "There is currently a single intrinsic mapping type:" msgstr "Actualmente hay un único tipo de mapeo intrínseco:" #: ../Doc/reference/datamodel.rst:464 msgid "Dictionaries" msgstr "Diccionarios" #: ../Doc/reference/datamodel.rst:436 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:445 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:450 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:457 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:461 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:726 msgid "Callable types" msgstr "Tipos invocables" #: ../Doc/reference/datamodel.rst:473 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:579 msgid "User-defined functions" msgstr "Funciones definidas por el usuario" #: ../Doc/reference/datamodel.rst:482 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:487 ../Doc/reference/datamodel.rst:841 msgid "Special attributes:" msgstr "Atributos especiales:" #: ../Doc/reference/datamodel.rst:505 msgid "Attribute" msgstr "Atributo" #: ../Doc/reference/datamodel.rst:505 msgid "Meaning" msgstr "Significado" #: ../Doc/reference/datamodel.rst:507 ../Doc/reference/datamodel.rst:762 #: ../Doc/reference/datamodel.rst:857 msgid ":attr:`__doc__`" msgstr ":attr:`__doc__`" #: ../Doc/reference/datamodel.rst:507 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:507 ../Doc/reference/datamodel.rst:512 #: ../Doc/reference/datamodel.rst:515 ../Doc/reference/datamodel.rst:520 #: ../Doc/reference/datamodel.rst:524 ../Doc/reference/datamodel.rst:530 #: ../Doc/reference/datamodel.rst:540 ../Doc/reference/datamodel.rst:551 #: ../Doc/reference/datamodel.rst:561 msgid "Writable" msgstr "Escribible" #: ../Doc/reference/datamodel.rst:512 msgid ":attr:`~definition.\\ __name__`" msgstr ":attr:`~definition.\\ __name__`" #: ../Doc/reference/datamodel.rst:512 msgid "The function's name." msgstr "El nombre de la función." #: ../Doc/reference/datamodel.rst:515 msgid ":attr:`~definition.\\ __qualname__`" msgstr ":attr:`~definition.\\ __qualname__`" #: ../Doc/reference/datamodel.rst:515 msgid "The function's :term:`qualified name`." msgstr "Las funciones :term:`qualified name`." #: ../Doc/reference/datamodel.rst:520 ../Doc/reference/datamodel.rst:847 msgid ":attr:`__module__`" msgstr ":attr:`__module__`" #: ../Doc/reference/datamodel.rst:520 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:524 msgid ":attr:`__defaults__`" msgstr ":attr:`__defaults__`" #: ../Doc/reference/datamodel.rst:524 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:530 msgid ":attr:`__code__`" msgstr ":attr:`__code__`" #: ../Doc/reference/datamodel.rst:530 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:533 msgid ":attr:`__globals__`" msgstr ":attr:`__globals__`" #: ../Doc/reference/datamodel.rst:533 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:533 ../Doc/reference/datamodel.rst:544 msgid "Read-only" msgstr "Solo lectura" #: ../Doc/reference/datamodel.rst:540 ../Doc/reference/datamodel.rst:850 msgid ":attr:`~object.__dict__`" msgstr ":attr:`~object.__dict__`" #: ../Doc/reference/datamodel.rst:540 msgid "The namespace supporting arbitrary function attributes." msgstr "El espacio de nombres que admite atributos de funciones arbitrarias." #: ../Doc/reference/datamodel.rst:544 msgid ":attr:`__closure__`" msgstr ":attr:`__closure__`" #: ../Doc/reference/datamodel.rst:544 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:551 ../Doc/reference/datamodel.rst:777 #: ../Doc/reference/datamodel.rst:864 msgid ":attr:`__annotations__`" msgstr ":attr:`__annotations__`" #: ../Doc/reference/datamodel.rst:551 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:561 msgid ":attr:`__kwdefaults__`" msgstr ":attr:`__kwdefaults__`" #: ../Doc/reference/datamodel.rst:561 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:565 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:567 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:573 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:576 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:642 msgid "Instance methods" msgstr "Métodos de instancia" #: ../Doc/reference/datamodel.rst:587 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:597 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:603 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:606 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:610 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:616 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:621 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:628 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:633 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:657 msgid "Generator functions" msgstr "Funciones generadoras" #: ../Doc/reference/datamodel.rst:649 #, fuzzy 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 declaración :keyword:`yield` (ver " "sección :ref:`yield`) se llama :dfn:`generator function`. Dicha función, " "cuando es invocada, siempre retorna un objeto iterador que puede ser " "utilizado para ejecutar el cuerpo de la función: invocando el método " "iterador :meth:`iterator.__next__` hará que la función se ejecute hasta " "proporcionar un valor utilizando la declaración :keyword:`!yield`. Cuando " "la función ejecuta una declaración :keyword:`return` o llega hasta el final, " "una excepción :exc:`StopIteration` es lanzada y el iterador habrá llegado al " "final del conjunto de valores a ser retornados." #: ../Doc/reference/datamodel.rst:667 msgid "Coroutine functions" msgstr "Funciones de corrutina" #: ../Doc/reference/datamodel.rst:663 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:687 msgid "Asynchronous generator functions" msgstr "Funciones generadoras asincrónicas" #: ../Doc/reference/datamodel.rst:674 #, fuzzy 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 es definido usando :keyword:`async def` y que " "utiliza la declaración :keyword:`yield` se llama :dfn:`asynchronous " "generator function`. Dicha función, al ser invocada, retorna un objeto " "iterador asincrónico que puede ser utilizado en una declaración :keyword:" "`async for` para ejecutar el cuerpo de la función." #: ../Doc/reference/datamodel.rst:680 #, fuzzy 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 "" "Invocando el método del iterador asincrónico :meth:`aiterator.__anext__` " "retornará un :term:`awaitable` que al ser esperado se ejecutará hasta " "proporcionar un valor utilizando la expresión :keyword:`yield`. Cuando la " "función ejecuta una declaración :keyword:`return` vacía o llega a su final, " "una excepción :exc:`StopAsyncIteration` es lanzada y el iterador asincrónico " "habrá llegado al final del conjunto de valores a ser producidos." #: ../Doc/reference/datamodel.rst:702 msgid "Built-in functions" msgstr "Funciones incorporadas" #: ../Doc/reference/datamodel.rst:695 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:714 msgid "Built-in methods" msgstr "Métodos incorporados" #: ../Doc/reference/datamodel.rst:710 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:721 msgid "Classes" msgstr "Clases" #: ../Doc/reference/datamodel.rst:717 #, fuzzy 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 " "de nuevas instancias de ellos mismos, pero las variaciones son posibles para " "los tipos de clases que anulan :meth:`__new__`. Los argumentos de la " "invocación son pasados a :meth:`__new__` y, en el caso típico, a :meth:" "`__init__` para iniciar la nueva instancia." #: ../Doc/reference/datamodel.rst:726 msgid "Class Instances" msgstr "Instancias de clases" #: ../Doc/reference/datamodel.rst:724 #, fuzzy 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 " "el método :meth:`__call__` en su clase." #: ../Doc/reference/datamodel.rst:789 msgid "Modules" msgstr "Módulos" #: ../Doc/reference/datamodel.rst:733 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:745 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:755 msgid "Predefined (writable) attributes:" msgstr "Atributos predefinidos (escribibles):" #: ../Doc/reference/datamodel.rst:758 msgid ":attr:`__name__`" msgstr ":attr:`__name__`" #: ../Doc/reference/datamodel.rst:758 msgid "The module's name." msgstr "El nombre del módulo." #: ../Doc/reference/datamodel.rst:761 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:771 msgid ":attr:`__file__`" msgstr ":attr:`__file__`" #: ../Doc/reference/datamodel.rst:765 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:774 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:781 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:786 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:864 msgid "Custom classes" msgstr "Clases personalizadas" #: ../Doc/reference/datamodel.rst:792 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:816 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:826 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:831 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:844 msgid ":attr:`~definition.__name__`" msgstr ":attr:`~definition.__name__`" #: ../Doc/reference/datamodel.rst:844 msgid "The class name." msgstr "El nombre de la clase." #: ../Doc/reference/datamodel.rst:847 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:850 msgid "The dictionary containing the class's namespace." msgstr "El diccionario conteniendo el espacio de nombres de la clase." #: ../Doc/reference/datamodel.rst:854 msgid ":attr:`~class.__bases__`" msgstr ":attr:`~class.__bases__`" #: ../Doc/reference/datamodel.rst:853 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:857 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:860 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:907 msgid "Class instances" msgstr "Instancias de clase" #: ../Doc/reference/datamodel.rst:873 #, fuzzy 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 es creado al invocar un objeto de clase (ver " "arriba). Una instancia de clase tiene implementado un espacio de nombres " "como diccionario que es el primer lugar en el que se buscan referencias de " "atributos. Cuando un atributo no es encontrado ahí, y la clase de instancia " "tiene un atributo con ese nombre, la búsqueda continúa con los atributos de " "clase. Si se encuentra que un atributo de clase es un objeto de función " "definido por el usuario, es transformado en un objeto de método de instancia " "cuyo atributo :attr:`__self__` es la instancia. Los objetos de método y " "método de clase estáticos también son transformados; ver más adelante debajo " "de “Clases”. Ver sección :ref:`descriptors` para otra forma en la que los " "atributos de una clase obtenida a través de sus instancias puede 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:`__getattr__`, éste es llamado para satisfacer la " "búsqueda." #: ../Doc/reference/datamodel.rst:889 #, fuzzy 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 "" "Asignación y eliminación de atributos actualizan el diccionario de la " "instancia, nunca el diccionario de la clase. Si la clase tiene un método :" "meth:`__setattr__` o :meth:`__delattr__`, éste es invocado en lugar de " "actualizar el diccionario de la instancia directamente." #: ../Doc/reference/datamodel.rst:899 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:906 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:933 msgid "I/O objects (also known as file objects)" msgstr "Objetos E/S (también conocidos como objetos de archivo)" #: ../Doc/reference/datamodel.rst:923 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:929 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:1219 msgid "Internal types" msgstr "Tipos internos" #: ../Doc/reference/datamodel.rst:940 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:1050 msgid "Code objects" msgstr "Objetos de código" #: ../Doc/reference/datamodel.rst:947 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:975 #, fuzzy 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); :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` da el nombre de la " "función; :attr:`co_argcount` es el número total de argumentos posicionales " "(incluyendo argumentos únicamente posicionales y argumentos con valores por " "default); :attr:`co_posonlyargcount` es el número de argumentos únicamente " "posicionales (incluyendo argumentos con valores por default); :attr:" "`co_kwonlyargcountp` es el número de argumentos solo de palabra clave " "(incluyendo argumentos con valores por default); :attr:`co_nlocals` es el " "número de variables usadas por la función (incluyendo argumentos); :attr:" "`co_varnames` es una tupla que contiene los nombres con las variables " "locales (empezando con los nombres de argumento); :attr:`co_cellvars` es una " "tupla que contiene los nombres de variables locales que son referenciadas " "por funciones anidadas; :attr:`co_freevars` es una tupla que contiene los " "nombres de variables libres; :attr:`co_code` es una cadena que representa la " "secuencia de instrucciones de bytecode; :attr:`co_consts` es una tupla que " "contiene las literales usadas por el bytecode; :attr:`co_names` es una tupla " "que contiene los nombres usados por el bytecode; :attr:`co_filename` es el " "nombre de archivo de donde el código fue compilado; :attr:`co_firstlineno` " "es el primer número de línea de la función; :attr:`co_lnotab` es una cadena " "codificando el mapeo desde el desplazamiento de bytecode al número de líneas " "(ver el código fuente del intérprete para más detalles); :attr:" "`co_stacksize` es el tamaño de pila requerido; :attr:`co_flags` es un entero " "codificando el número de banderas para el intérprete." #: ../Doc/reference/datamodel.rst:1000 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:1006 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:1012 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:1016 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:1021 msgid "" "Returns an iterable over the source code positions of each bytecode " "instruction in the code object." msgstr "" #: ../Doc/reference/datamodel.rst:1024 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 "" #: ../Doc/reference/datamodel.rst:1030 msgid "" "This positional information can be missing. A non-exhaustive lists of cases " "where this may happen:" msgstr "" #: ../Doc/reference/datamodel.rst:1033 msgid "Running the interpreter with :option:`-X` ``no_debug_ranges``." msgstr "" #: ../Doc/reference/datamodel.rst:1034 msgid "" "Loading a pyc file compiled while using :option:`-X` ``no_debug_ranges``." msgstr "" #: ../Doc/reference/datamodel.rst:1035 msgid "Position tuples corresponding to artificial instructions." msgstr "" #: ../Doc/reference/datamodel.rst:1036 msgid "" "Line and column numbers that can't be represented due to implementation " "specific limitations." msgstr "" #: ../Doc/reference/datamodel.rst:1039 msgid "" "When this occurs, some or all of the tuple elements can be :const:`None`." msgstr "" #: ../Doc/reference/datamodel.rst:1045 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 "" #: ../Doc/reference/datamodel.rst:1112 msgid "Frame objects" msgstr "Objetos de marco" #: ../Doc/reference/datamodel.rst:1057 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:1068 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:1076 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:1085 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:1090 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:1095 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:1100 msgid "Frame objects support one method:" msgstr "Objetos de marco soportan un método:" #: ../Doc/reference/datamodel.rst:1104 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:1110 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:1175 msgid "Traceback objects" msgstr "Objetos de seguimiento de pila (traceback)" #: ../Doc/reference/datamodel.rst:1127 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:1131 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:1139 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:1144 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:1154 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:1163 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:1169 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:1173 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:1202 msgid "Slice objects" msgstr "Objetos de segmento (Slice objects)" #: ../Doc/reference/datamodel.rst:1180 #, fuzzy 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 segmento son utilizados para representar segmentos para " "métodos :meth:`__getitem__`. También son creados por la función incorporada :" "func:`slice`." #: ../Doc/reference/datamodel.rst:1189 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:1193 msgid "Slice objects support one method:" msgstr "Los objetos de segmento soportan un método:" #: ../Doc/reference/datamodel.rst:1197 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:1211 msgid "Static method objects" msgstr "Objetos de método estático" #: ../Doc/reference/datamodel.rst:1205 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:1219 msgid "Class method objects" msgstr "Objetos de método de clase" #: ../Doc/reference/datamodel.rst:1214 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:1224 msgid "Special method names" msgstr "Nombres especiales de método" #: ../Doc/reference/datamodel.rst:1230 #, fuzzy 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 son invocadas por " "sintaxis especiales (como operaciones aritméticas o de sub-índice y " "segmentación) definiendo métodos con nombres especiales. Este es el enfoque " "de Python hacia :dfn:`operator overloading`, permitiendo a las clases " "definir su propio comportamiento con respecto a los operadores del lenguaje. " "Por ejemplo, si una clase define un método llamado :meth:`__getitem__`, y " "``x`` es una instancia de esta clase, entonces ``x[i]`` es aproximadamente " "equivalente a ``type(x).__getitem__(x, i)``. A excepción de donde se " "menciona, los intentos por ejecutar una operación lanzan una excepción " "cuando no es definido un método apropiado (normalmente :exc:`AttributeError` " "o :exc:`TypeError`)." #: ../Doc/reference/datamodel.rst:1241 #, fuzzy 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 "" "Estableciendo un método especial a ``None`` indica que la operación " "correspondiente no se encuentra disponible. Por ejemplo, si una clase " "establece :meth:`__iter__` a ``None``, la clase no es iterable, así que " "llamando :func:`iter` en sus instancias lanzará un :exc:`TypeError` (sin " "volver a :meth:`__getitem__`). [#]_" #: ../Doc/reference/datamodel.rst:1247 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:1258 msgid "Basic customization" msgstr "Personalización básica" #: ../Doc/reference/datamodel.rst:1264 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:1271 #, fuzzy 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 "" "Implementaciones típicas crean una nueva instancia de la clase invocando el " "método :meth:`__new__` de la súper clase utilizando ``super().__new__(cls[, " "…])`` con argumentos apropiados y después modificando la recién creada " "instancia como necesaria antes de retornarla." #: ../Doc/reference/datamodel.rst:1276 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:1281 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:1284 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:1293 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:1300 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:1313 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:1319 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:1326 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:1331 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:1336 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 "" #: ../Doc/reference/datamodel.rst:1346 msgid "Documentation for the :mod:`gc` module." msgstr "Documentación para el módulo :mod:`gc`." #: ../Doc/reference/datamodel.rst:1350 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:1354 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:1360 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:1375 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:1384 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:1395 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:1400 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:1404 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:1414 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:1425 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:1435 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:1437 msgid "The return value must be a string object." msgstr "El valor de retorno debe ser un objeto de cadena." #: ../Doc/reference/datamodel.rst:1439 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:1443 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:1459 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:1465 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:1472 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:1548 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:1557 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:1562 #, fuzzy 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://www.ocert.org/advisories/" "ocert-2011-003.html for details." msgstr "" "Esto tiene la intención de proveer protección contra una negación de " "servicio causada por entradas cautelosamente elegidas y que explotan el peor " "caso de rendimiento en la inserción de un diccionario, complejidad O(n\\ :" "sup:`2`). Ver http://www.ocert.org/advisories/ocert-2011-003.html para más " "detalles." #: ../Doc/reference/datamodel.rst:1567 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:1571 msgid "See also :envvar:`PYTHONHASHSEED`." msgstr "Ver también :envvar:`PYTHONHASHSEED`." #: ../Doc/reference/datamodel.rst:1573 msgid "Hash randomization is enabled by default." msgstr "La aleatorización de hash es habilitada por defecto." #: ../Doc/reference/datamodel.rst:1581 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:`__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 "" "Es llamado para implementar pruebas de valores de verdad y la operación " "incorporada ``bool()``; debe retornar ``False`` o ``True``. Cuando este " "método no es definido, :meth:`__len__` es llamado, si es definido, y el " "objeto es considerado verdadero (*true*) si el resultado es diferente de " "zero. Si la clase no define :meth:`__len__` ni :meth:`__bool__`, todas sus " "instancias son consideradas verdaderas (*true*)." #: ../Doc/reference/datamodel.rst:1592 msgid "Customizing attribute access" msgstr "Personalizando acceso a atributos" #: ../Doc/reference/datamodel.rst:1594 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:1602 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:1609 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:1622 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:1633 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:1637 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:1639 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:1646 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:1650 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:1654 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:1656 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:1663 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:1666 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:1668 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:1675 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:1680 msgid "Customizing module attribute access" msgstr "Personalizando acceso a atributos de módulo" #: ../Doc/reference/datamodel.rst:1687 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:1696 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:1700 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:1718 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:1723 msgid "``__class__`` module attribute is now writable." msgstr "El atributo de módulo ``__class__`` es ahora escribible." #: ../Doc/reference/datamodel.rst:1726 msgid "``__getattr__`` and ``__dir__`` module attributes." msgstr "Atributos de módulo ``__getattr__`` y ``__dir__``." #: ../Doc/reference/datamodel.rst:1731 msgid ":pep:`562` - Module __getattr__ and __dir__" msgstr ":pep:`562` - Módulos __getattr__ y __dir__" #: ../Doc/reference/datamodel.rst:1732 msgid "Describes the ``__getattr__`` and ``__dir__`` functions on modules." msgstr "Describe las funciones ``__getattr__`` y ``__dir__`` en módulos." #: ../Doc/reference/datamodel.rst:1738 msgid "Implementing Descriptors" msgstr "Implementando Descriptores" #: ../Doc/reference/datamodel.rst:1740 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:1750 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:1756 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:1759 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:1768 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:1771 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:1777 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:1780 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:1791 msgid "Invoking Descriptors" msgstr "Invocando Descriptores" #: ../Doc/reference/datamodel.rst:1793 #, fuzzy 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 "" "De manera general, un descriptor es un atributo de objeto con " "“comportamiento enlazado”, cuyo atributo de acceso ha sido anulado por " "métodos en el protocolo del descriptor: :meth:`__get__`, :meth:`__set__`, y :" "meth:`__delete__`. Si cualquiera de esos métodos son definidos por un " "objeto, se dice que es un descriptor." #: ../Doc/reference/datamodel.rst:1799 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:1804 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:1809 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:1814 msgid "Direct Call" msgstr "Llamado Directo" #: ../Doc/reference/datamodel.rst:1813 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:1818 msgid "Instance Binding" msgstr "Enlace de Instancia" #: ../Doc/reference/datamodel.rst:1817 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:1822 msgid "Class Binding" msgstr "Enlace de Clase" #: ../Doc/reference/datamodel.rst:1821 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:1828 msgid "Super Binding" msgstr "Súper Enlace" #: ../Doc/reference/datamodel.rst:1825 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 "" #: ../Doc/reference/datamodel.rst:1862 #, fuzzy 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 "" "Para enlace de instancias, la precedencia de la invocación de descriptor " "depende de qué métodos de descriptor son definidos. Un descriptor puede " "definir cualquier combinación de :meth:`__get__`, :meth:`__set__` y :meth:" "`__delete__`. Si no define :meth:`__get__`, entonces el acceso al atributo " "retornará el objeto de descriptor a menos que exista un valor en el " "diccionario de instancias del objeto. Si el descriptor define :meth:" "`__set__` y/o :meth:`__delete__`, es un descriptor de datos; si no define " "ninguno, es un descriptor sin datos. Normalmente los descriptores de datos " "definen ambos :meth:`__get__` y :meth:`__set__`, mientras que los " "descriptores sin datos solo tienen el método :meth:`__get__`. Descriptores " "de datos con :meth:`__set__` y :meth:`__get__` (y/o :meth:`__delete__`) " "definidos siempre anulan una re-definición en el diccionario de instancias. " "Por el contrario, los descriptores sin datos pueden ser anulados por " "instancias." #: ../Doc/reference/datamodel.rst:1876 #, fuzzy 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 "" "Métodos de Python (que incluyen :func:`staticmethod` y :func:`classmethod`) " "son implementados como descriptores sin datos. Por consiguiente, las " "instancias pueden redefinir y anular métodos. Esto permite que instancias " "individuales adquieran comportamientos que pueden diferir de otras " "instancias de la misma clase." #: ../Doc/reference/datamodel.rst:1882 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:1889 msgid "__slots__" msgstr "__slots__" #: ../Doc/reference/datamodel.rst:1891 #, fuzzy 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 permiten declarar de manera explícita miembros de datos " "(como propiedades) y negar la creación de *__dict__* y *__weakref__* (a " "menos que se declare explícitamente en *__slots__* o se encuentre disponible " "en un elemento padre.)" #: ../Doc/reference/datamodel.rst:1895 #, fuzzy msgid "" "The space saved over using :attr:`~object.__dict__` can be significant. " "Attribute lookup speed can be significantly improved as well." msgstr "" "El espacio ganado al usar *__dict__* puede ser importante. La velocidad de " "búsqueda de atributos también puede mejorar significativamente." #: ../Doc/reference/datamodel.rst:1900 #, fuzzy 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 "" "Esta variable de clase se le puede asignar una cadena de caracteres, un " "elemento iterable o una secuencia de cadena de caracteres con nombres de " "variables utilizados por instancias. *__slots__* reserva espacio para las " "variables declaradas y previene la creación automática de *__dict__* y " "*__weakref__* para cada instancia." #: ../Doc/reference/datamodel.rst:1908 msgid "Notes on using *__slots__*" msgstr "Notas sobre el uso de *__slots__*" #: ../Doc/reference/datamodel.rst:1910 #, fuzzy msgid "" "When inheriting from a class without *__slots__*, the :attr:`~object." "__dict__` and *__weakref__* attribute of the instances will always be " "accessible." msgstr "" "Cuando se hereda de una clase sin *__slots__*, los atributos *__dict__* y " "*__weakref__* de las instancias siempre serán accesibles." #: ../Doc/reference/datamodel.rst:1914 #, fuzzy 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 *__dict__*, no se puede asignar a instancias nuevas " "variables que no se encuentren listadas en la definición de *__slots__*. " "Intentos de asignación a una variable no listada lanza una excepción :exc:" "`AttributeError`. Si se desea hacer una asignación dinámica a variables " "nuevas, se debe agregar ``’__dict__’`` a la secuencia de cadena de " "caracteres en la declaración de *__slots__*." #: ../Doc/reference/datamodel.rst:1921 #, fuzzy 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__* por cada instancia, las clases que definen " "*__slots__* no soportan “referencias débiles” (*weak references*) a sus " "instancias. Si se desea el soporte de dichas referencias, se debe agregar " "``’__weakref__’`` a la secuencia de cadena de caracteres en la declaración " "de *__slots__*." #: ../Doc/reference/datamodel.rst:1927 #, fuzzy 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__* son implementados a nivel de clase al crear descriptores (:ref:" "`descriptors`) para cada nombre de variable. Como resultado, los atributos " "de clase no pueden ser utilizados para establecer valores por defecto a " "variables de instancia definidos por *__slots__*; de lo contrario, el " "atributo de clase sobrescribirá la asignación del descriptor." #: ../Doc/reference/datamodel.rst:1933 #, fuzzy 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 está limitada a la clase donde " "fue definida. *__slots__* declarado en padres, se vuelven disponibles en " "clases hijas. Sin embargo, subclases hijas tendrán un *__dict__* y " "*__weakref__* a menos que también se defina *__slots__* (el cual solo debe " "contener nombres de espacios o *slots* *adicionales*)." #: ../Doc/reference/datamodel.rst:1939 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:1944 msgid "" "Nonempty *__slots__* does not work for classes derived from \"variable-" "length\" built-in types such as :class:`int`, :class:`bytes` and :class:" "`tuple`." msgstr "" "*__slots__* no vacíos no funcionan para clases derivadas de tipos " "incorporados de “longitud variable” como :class:`int`, :class:`bytes` y :" "class:`tuple`." #: ../Doc/reference/datamodel.rst:1947 msgid "Any non-string :term:`iterable` may be assigned to *__slots__*." msgstr "" #: ../Doc/reference/datamodel.rst:1949 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 "" #: ../Doc/reference/datamodel.rst:1954 #, fuzzy msgid "" ":attr:`~instance.__class__` assignment works only if both classes have the " "same *__slots__*." msgstr "" "La asignación *__class__* funciona solo si ambas clases tienen el mismo " "*__slots__*." #: ../Doc/reference/datamodel.rst:1957 #, fuzzy 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 "" "Herencia múltiple con múltiples clases de padres con espacios (*slots*) " "puede ser utilizada, pero solo un padre es permitido que tenga atributos " "creados por espacios (las otras bases deben tener diseños de espacios " "vacíos) - violaciones lanzan una excepción :exc:`TypeError`." #: ../Doc/reference/datamodel.rst:1963 #, fuzzy 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 un iterados es utilizado por *__slots__*, entonces un descriptor es " "creado para cada uno de los valores del iterador. Sin embargo, el atributo " "*__slots__* será un iterador vacío." #: ../Doc/reference/datamodel.rst:1971 msgid "Customizing class creation" msgstr "Personalización de creación de clases" #: ../Doc/reference/datamodel.rst:1973 #, fuzzy 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, *__init_subclass__* es llamado " "en esa clase. De esta manera, es posible escribir clases que cambian el " "comportamiento de las subclases. Esto está estrechamente relacionado con los " "decoradores de clase, pero solo donde los decoradores de clase afectan a la " "clase específica a la que son aplicados, ``__init_subclass__`` solo aplica a " "futuras subclases de la clase que define el método." #: ../Doc/reference/datamodel.rst:1982 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:1986 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:2000 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:2005 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:2013 #, fuzzy 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 retornos de llamada a aquellas con un gancho :meth:" "`__set_name__`." #: ../Doc/reference/datamodel.rst:2018 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:2024 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:2035 msgid "See :ref:`class-object-creation` for more details." msgstr "Ver :ref:`class-object-creation` para más detalles." #: ../Doc/reference/datamodel.rst:2043 msgid "Metaclasses" msgstr "Metaclases" #: ../Doc/reference/datamodel.rst:2050 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:2054 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:2068 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:2071 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:2073 msgid "MRO entries are resolved;" msgstr "Entradas de la Orden de Resolución de Método (MRU) son resueltas;" #: ../Doc/reference/datamodel.rst:2074 msgid "the appropriate metaclass is determined;" msgstr "se determina la metaclase adecuada;" #: ../Doc/reference/datamodel.rst:2075 msgid "the class namespace is prepared;" msgstr "se prepara el espacio de nombres de clase;" #: ../Doc/reference/datamodel.rst:2076 msgid "the class body is executed;" msgstr "se ejecuta el cuerpo de la clase;" #: ../Doc/reference/datamodel.rst:2077 msgid "the class object is created." msgstr "se crea el objeto de clase." #: ../Doc/reference/datamodel.rst:2081 msgid "Resolving MRO entries" msgstr "Resolviendo entradas de la Orden de Resolución de Métodos (MRU)" #: ../Doc/reference/datamodel.rst:2083 msgid "" "If a base that appears in class definition is not an instance of :class:" "`type`, then an ``__mro_entries__`` method is searched on it. If found, it " "is called with the original bases tuple. This method must return a tuple of " "classes that will be used instead of this base. The tuple may be empty, in " "such case the original base is ignored." msgstr "" "Si una base que aparece en la definición de una clase no es una instancia " "de :class:`type`, entonces el método ``__mro_entries__`` se busca en ella. " "Si es encontrado, se llama con la tupla de bases originales. Este método " "debe retornar una tupla de clases que será utilizado en lugar de esta base. " "La tupla puede estar vacía, en cuyo caso la base original es ignorada." #: ../Doc/reference/datamodel.rst:2091 msgid ":pep:`560` - Core support for typing module and generic types" msgstr "" ":pep:`560` - Soporte central para módulos de clasificación y tipos genéricos" #: ../Doc/reference/datamodel.rst:2095 msgid "Determining the appropriate metaclass" msgstr "Determinando la metaclase adecuada" #: ../Doc/reference/datamodel.rst:2099 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:2101 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:2102 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:2104 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:2107 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:2117 msgid "Preparing the class namespace" msgstr "Preparando el espacio de nombres de la clase" #: ../Doc/reference/datamodel.rst:2122 #, fuzzy 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 apropiada, entonces se prepara " "el espacio de nombres de la clase. Si la metaclase tiene un atributo " "``__prepare__``, es llamado como ``namespace = metaclass.__prepare__(name, " "bases, **kwds)`` (donde los argumentos de palabra clave adicionales, de " "existir, provienen de la definición de la clase). El método ``__prepare__`` " "debe ser implementado como :func:`classmethod`. El espacio de nombres " "retornado por ``__prepare__`` es pasado a ``__new__``, pero cuando el objeto " "de clase final es creado, el espacio de nombres es copiado en un ``dict``." #: ../Doc/reference/datamodel.rst:2131 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:2136 msgid ":pep:`3115` - Metaclasses in Python 3000" msgstr ":pep:`3115` - Metaclases en Python 3000" #: ../Doc/reference/datamodel.rst:2137 msgid "Introduced the ``__prepare__`` namespace hook" msgstr "Introduce el enlace de espacio de nombres ``__prepare__``" #: ../Doc/reference/datamodel.rst:2141 msgid "Executing the class body" msgstr "Ejecutando el cuerpo de la clase" #: ../Doc/reference/datamodel.rst:2146 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:2152 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:2161 msgid "Creating the class object" msgstr "Creando el objeto de clase" #: ../Doc/reference/datamodel.rst:2168 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:2173 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:2183 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:2189 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:2193 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:2195 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:2197 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:2200 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:2204 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:2211 msgid ":pep:`3135` - New super" msgstr ":pep:`3135` - Nuevo súper" #: ../Doc/reference/datamodel.rst:2212 msgid "Describes the implicit ``__class__`` closure reference" msgstr "Describe la referencia de cierre implícita ``__class__``" #: ../Doc/reference/datamodel.rst:2216 msgid "Uses for metaclasses" msgstr "Usos para metaclases" #: ../Doc/reference/datamodel.rst:2218 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:2225 msgid "Customizing instance and subclass checks" msgstr "Personalizando revisiones de instancia y subclase" #: ../Doc/reference/datamodel.rst:2227 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:2230 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:2237 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:2244 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:2249 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:2260 msgid ":pep:`3119` - Introducing Abstract Base Classes" msgstr "" ":pep:`3119` - Introducción a Clases Base Abstractas (*Abstract Base Classes*)" #: ../Doc/reference/datamodel.rst:2257 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:2265 msgid "Emulating generic types" msgstr "Emulando tipos genéricos" #: ../Doc/reference/datamodel.rst:2267 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 "" #: ../Doc/reference/datamodel.rst:2275 msgid ":pep:`484` - Type Hints" msgstr "" #: ../Doc/reference/datamodel.rst:2275 msgid "Introducing Python's framework for type annotations" msgstr "" #: ../Doc/reference/datamodel.rst:2278 msgid ":ref:`Generic Alias Types`" msgstr "" #: ../Doc/reference/datamodel.rst:2278 msgid "Documentation for objects representing parameterized generic classes" msgstr "" #: ../Doc/reference/datamodel.rst:2281 msgid "" ":ref:`Generics`, :ref:`user-defined generics` and :" "class:`typing.Generic`" msgstr "" #: ../Doc/reference/datamodel.rst:2281 msgid "" "Documentation on how to implement generic classes that can be parameterized " "at runtime and understood by static type-checkers." msgstr "" #: ../Doc/reference/datamodel.rst:2284 msgid "" "A class can *generally* only be parameterized if it defines the special " "class method ``__class_getitem__()``." msgstr "" #: ../Doc/reference/datamodel.rst:2289 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:2292 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 "" #: ../Doc/reference/datamodel.rst:2298 msgid "The purpose of *__class_getitem__*" msgstr "" #: ../Doc/reference/datamodel.rst:2300 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 "" #: ../Doc/reference/datamodel.rst:2304 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 "" #: ../Doc/reference/datamodel.rst:2310 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 "" #: ../Doc/reference/datamodel.rst:2320 msgid "*__class_getitem__* versus *__getitem__*" msgstr "" #: ../Doc/reference/datamodel.rst:2322 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 "" #: ../Doc/reference/datamodel.rst:2329 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 "" #: ../Doc/reference/datamodel.rst:2357 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 "" #: ../Doc/reference/datamodel.rst:2376 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 "" #: ../Doc/reference/datamodel.rst:2401 #, fuzzy msgid ":pep:`560` - Core Support for typing module and generic types" msgstr "" ":pep:`560` - Soporte central para módulos de clasificación y tipos genéricos" #: ../Doc/reference/datamodel.rst:2400 msgid "" "Introducing :meth:`~object.__class_getitem__`, and outlining when a :ref:" "`subscription` results in ``__class_getitem__()`` being " "called instead of :meth:`~object.__getitem__`" msgstr "" #: ../Doc/reference/datamodel.rst:2408 msgid "Emulating callable objects" msgstr "Emulando objetos que se pueden llamar" #: ../Doc/reference/datamodel.rst:2415 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:2422 msgid "Emulating container types" msgstr "Emulando tipos de contenedores" #: ../Doc/reference/datamodel.rst:2424 #, fuzzy 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 "" "Los siguientes métodos pueden ser definidos para implementar objetos " "contenedores. Los contenedores son generalmente secuencias (como listas o " "tuplas) o mapeos (como diccionarios), pero también pueden representar otros " "contenedores. La primera colección de métodos es utilizada ya sea para " "emular una secuencia o para emular un mapeo; la diferencia es que para una " "secuencia, las llaves permitidas deben ser los enteros *k* por lo que ``0 <= " "k < N`` donde *N* es la longitud de la secuencia, o secciones de objetos, " "los cuales definen un rango de elementos. También es recomendado que los " "mapeos 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` comportándose de manera similar a " "aquellos para los objetos de diccionario estándar de Python. El módulo :mod:" "`collections.abc` proporciona una clase base abstracta :class:`~collections." "abc.MutableMapping` que ayuda a crear aquellos métodos desde un conjunto " "base de :meth:`__getitem__`, :meth:`__setitem__`, :meth:`__delitem__`, y :" "meth:`keys`. Secuencias mutables deben proporcionar métodos :meth:`append`, :" "meth:`count`, :meth:`index`, :meth:`extend`, :meth:`insert`, :meth:`pop`, :" "meth:`remove`, :meth:`reverse` y :meth:`sort`, como objetos de lista " "estándar de Python. Por último, tipos de secuencia deben implementar adición " "(concatenación) y multiplicación (repetición) al definir los métodos :meth:" "`__add__`, :meth:`__radd__`, :meth:`__iadd__`, :meth:`__mul__`, :meth:" "`__rmul__` y :meth:`__imul__` descritos a continuación; no deben definir " "otros operadores numéricos. Es recomendado que ambos mapeos y secuencias " "implementen el método :meth:`__contains__` para permitir el uso eficiente " "del operador ``in``; para mapeos, ``in`` debe buscar las llaves de los " "mapeos; para secuencias, debe buscar a través de los valores. Además es " "recomendado que tanto mapeos como secuencias implementen el método :meth:" "`__iter__` para permitir una iteración eficiente por el contenedor; para " "mapeos, :meth:`__iter__` debe iterar a través de las llaves del objeto; para " "secuencias, debe iterar a través de los valores." #: ../Doc/reference/datamodel.rst:2464 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:`__bool__` method and whose :meth:`__len__` method returns " "zero is considered to be false in a Boolean context." msgstr "" "Es llamado para implementar la función incorporada :func:`len`. Debe " "retornar la longitud del objeto, un entero ``>=`` 0. También, un objeto que " "no define un método :meth:`__bool__` y cuyo método :meth:`__len__` retorna " "cero, es considerado como falso en un contexto booleano." #: ../Doc/reference/datamodel.rst:2471 msgid "" "In CPython, the length is required to be at most :attr:`sys.maxsize`. If the " "length is larger than :attr:`!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:" "`__bool__` method." msgstr "" "En CPython, se requiere que la longitud sea como mucho :attr:`sys.maxsize`. " "Si la longitud es más grande que :attr:`!sys.maxsize` algunas " "características (como :func:`len`) pueden lanzar una excepción :exc:" "`OverflowError`. Para prevenir lanzar una excepción :exc:`!OverflowError` al " "validar la verdad de un valor, un objeto debe definir un método :meth:" "`__bool__`." #: ../Doc/reference/datamodel.rst:2480 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:2494 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:2498 msgid "is translated to ::" msgstr "es traducido a ::" #: ../Doc/reference/datamodel.rst:2502 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:2507 #, fuzzy 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 "" "Es llamado para implementar la evaluación de ``self[key]``. Para tipos de " "secuencia, las llaves aceptadas deben ser enteros y objetos de segmento. Se " "debe tomar en cuenta que la interpretación especial de índices negativos (si " "la clase desea emular un tipo de secuencia) depende del método :meth:" "`__getitem__`. Si *key* es de un tipo apropiado, se puede lanzar una " "excepción :exc:`TypeError`; si es de un valor afuera de la colección de " "índices para la secuencia (después de alguna interpretación especial de " "valores negativos), se debe lanzar una excepción :exc:`IndexError`. Para " "tipos de mapeos, si falta *key* (no en el contenedor), la excepción :exc:" "`KeyError` debe ser lanzada." #: ../Doc/reference/datamodel.rst:2519 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:2524 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 "" #: ../Doc/reference/datamodel.rst:2532 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:2541 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:2550 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:2556 #, fuzzy 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 "" "Este método es llamado cuando se requiere un iterador para un contenedor. " "Este método debe retornar un nuevo objeto iterador que pueda iterar todos " "los objetos del contenedor. Para mapeos, debe iterar sobre las llaves del " "contenedor." #: ../Doc/reference/datamodel.rst:2564 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:2568 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:2575 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:2582 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:2586 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:2595 msgid "Emulating numeric types" msgstr "Emulando tipos numéricos" #: ../Doc/reference/datamodel.rst:2597 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:2623 #, fuzzy 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 son llamados para implementar las operaciones aritméticas " "binarias (``+``, ``-``, ``*``, ``@``, ``/``, ``//``, ``%``, :func:`divmod`, :" "func:`pow`, ``**``, ``<<``, ``>>``, ``&``, ``^``, ``|``). Por ejemplo, para " "evaluar la expresión ``x + y``, donde *x* es instancia de una clase que " "tiene un método :meth:`__add__`, ``x.__add__(y)`` es llamado. El método :" "meth:`__divmod__` debe ser el equivalente a usar :meth:`__floordiv__` y :" "meth:`__mod__`; no debe ser relacionado a :meth:`__truediv__`. Se debe tomar " "en cuenta que :meth:`__pow__` debe ser definido para aceptar un tercer " "argumento opcional si la versión ternaria de la función incorporada :func:" "`pow` es soportada." #: ../Doc/reference/datamodel.rst:2634 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:2657 #, fuzzy 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 son llamados para implementar las operaciones aritméticas " "binarias (``+``, ``-``, ``*``, ``@``, ``/``, ``//``, ``%``, :func:`divmod`, :" "func:`pow`, ``**``, ``<<``, ``>>``, ``&``, ``^``, ``|``) con operandos " "reflejados (intercambiados). Estas funciones son llamadas únicamente si el " "operando izquierdo no soporta la operación correspondiente [#]_ y los " "operandos son de tipos diferentes. [#]_ Por ejemplo, para evaluar la " "expresión ``x - y``, donde *y* es instancia de una clase que tiene un " "método :meth:`__rsub__`, ``y.__rsub__(x)`` es llamado si ``x.__sub__(y)`` " "retorna *NotImplemented*." #: ../Doc/reference/datamodel.rst:2669 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:2674 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:2695 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:2716 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:2729 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:2736 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:2742 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:2754 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:2760 msgid "" "The built-in function :func:`int` falls back to :meth:`__trunc__` if " "neither :meth:`__int__` nor :meth:`__index__` is defined." msgstr "" #: ../Doc/reference/datamodel.rst:2763 msgid "The delegation of :func:`int` to :meth:`__trunc__` is deprecated." msgstr "" #: ../Doc/reference/datamodel.rst:2770 msgid "With Statement Context Managers" msgstr "Gestores de Contexto en la Declaración *with*" #: ../Doc/reference/datamodel.rst:2772 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:2783 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:2786 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:2791 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:2798 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:2802 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:2806 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:2813 msgid ":pep:`343` - The \"with\" statement" msgstr ":pep:`343` - La declaración “with”" #: ../Doc/reference/datamodel.rst:2813 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:2820 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:2822 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 " "patterns, the class needs to define a *__match_args__* attribute." msgstr "" "Cuando se usa 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)`` generalmente no es válido sin soporte especial en " "``MyClass``. Para poder usar ese tipo de patrones, la clase necesita definir " "un atributo *__match_args__*." #: ../Doc/reference/datamodel.rst:2829 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:2835 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:2845 msgid ":pep:`634` - Structural Pattern Matching" msgstr ":pep:`634` - Coincidencia de patrones estructurales" #: ../Doc/reference/datamodel.rst:2846 msgid "The specification for the Python ``match`` statement." msgstr "La especificación para la declaración ``match`` de Python." #: ../Doc/reference/datamodel.rst:2852 msgid "Special method lookup" msgstr "Búsqueda de método especial" #: ../Doc/reference/datamodel.rst:2854 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:2869 #, fuzzy 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 fundamental detrás de este comportamiento yace en una serie de " "métodos especiales como :meth:`__hash__` y :meth:`__repr__` que son " "implementados por todos los objetos, incluyendo objetos de tipo. Si la " "búsqueda implícita de estos métodos usaran el proceso de búsqueda " "convencional, fallarían al ser invocados en el objeto de tipo mismo::" #: ../Doc/reference/datamodel.rst:2883 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:2892 #, fuzzy 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 sobrepasar cualquier atributo de instancia en aras de lo " "apropiado, la búsqueda implícita del método especial generalmente también " "sobrepasa al método :meth:`__getattribute__` incluso de la metaclase del " "objeto::" #: ../Doc/reference/datamodel.rst:2918 #, fuzzy 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 "" "Sobrepasar el mecanismo de :meth:`__getattribute__` de esta forma " "proporciona un alcance importante para optimizaciones de velocidad dentro " "del intérprete, a costa de cierta flexibilidad en el manejo de métodos " "especiales (el método especial *debe* ser establecido en el objeto de clase " "mismo para ser invocado consistentemente por el intérprete)." #: ../Doc/reference/datamodel.rst:2929 msgid "Coroutines" msgstr "Corrutinas" #: ../Doc/reference/datamodel.rst:2933 msgid "Awaitable Objects" msgstr "Objetos Esperables" #: ../Doc/reference/datamodel.rst:2935 #, fuzzy 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 a un método :meth:" "`__await__`. :term:`Objetos Coroutine ` retornados a partir de " "funciones :keyword:`async def` son esperables." #: ../Doc/reference/datamodel.rst:2941 #, fuzzy 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 a partir de generadores " "decorados con :func:`types.coroutine` o :func:`asyncio.coroutine` también " "son esperables, pero no implementan :meth:`__await__`." #: ../Doc/reference/datamodel.rst:2947 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:2953 msgid ":pep:`492` for additional information about awaitable objects." msgstr ":pep:`492` para información adicional sobre objetos esperables." #: ../Doc/reference/datamodel.rst:2959 msgid "Coroutine Objects" msgstr "Objetos de Corrutina" #: ../Doc/reference/datamodel.rst:2961 #, fuzzy 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:`Objetos Coroutine ` son objetos :term:`awaitable`. La " "ejecución de una corrutina puede ser controlada llamando :meth:`__await__` e " "iterando sobre el resultado. Cuando la corrutina ha terminado de ejecutar y " "retorna, el iterados lanza una excepción :exc:`StopIteration`, y el " "atributo :attr:`~StopIteration.value` de dicha excepción mantiene el valor " "de retorno. Si la corrutina lanza una excepción, ésta es propagada por el " "iterador. Las corrutinas no deben lanzar directamente excepciones :exc:" "`StopIteration` no manejadas." #: ../Doc/reference/datamodel.rst:2969 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:2973 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:2979 #, fuzzy 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 continua la ejecución de una corrutina. Si *value* es ``None``, " "esto es equivalente a avanzar al iterador retornado por :meth:`__await__`. " "Si *value* no es ``None``, este método delega al método :meth:`~generator." "send` del iterador que causó la suspensión de la corrutina. El resultado (el " "valor de retorno, :exc:`StopIteration`, u otra excepción) es el mismo que " "cuando se itera sobre el valor de retorno de :meth:`__await__`, descrito " "anteriormente." #: ../Doc/reference/datamodel.rst:2990 #, fuzzy 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 "" "Lanza la excepción especificada en la corrutina. Este método delega a :meth:" "`~generator.throw` del iterador que causó la suspensión de la corrutina, si " "dicho método existe. De lo contrario, la excepción es lanzada al punto de la " "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 de :" "meth:`__await__` descrito anteriormente. Si la excepción no es obtenida en " "la corrutina, ésta se propaga de regreso a quien realizó el llamado." #: ../Doc/reference/datamodel.rst:3001 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:3009 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:3015 msgid "Asynchronous Iterators" msgstr "Iteradores asíncronos" #: ../Doc/reference/datamodel.rst:3017 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:3020 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:3024 msgid "Must return an *asynchronous iterator* object." msgstr "Debe retornar un objeto de *iterador asíncrono*." #: ../Doc/reference/datamodel.rst:3028 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:3031 msgid "An example of an asynchronous iterable object::" msgstr "Un ejemplo de objeto iterable asíncrono::" #: ../Doc/reference/datamodel.rst:3048 #, fuzzy 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, ``__aiter__`` podía retornar un *esperable* que se " "resolvería en un :term:`asynchronous iterator `." #: ../Doc/reference/datamodel.rst:3053 #, fuzzy 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, ``__aiter__`` debe retornar un objeto iterador " "asíncrono. Retornar cualquier otra cosa resultará en un error :exc:" "`TypeError`." #: ../Doc/reference/datamodel.rst:3061 msgid "Asynchronous Context Managers" msgstr "Gestores de Contexto Asíncronos" #: ../Doc/reference/datamodel.rst:3063 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:3066 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:3070 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:3075 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:3078 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:3091 msgid "Footnotes" msgstr "Notas a pie de página" #: ../Doc/reference/datamodel.rst:3092 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:3096 #, fuzzy 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:`__hash__`, :meth:`__iter__`, :meth:`__reversed__`, y :" "meth:`__contains__` tienen manejo especial para esto; otros lanzarán un " "error :exc:`TypeError`, pero lo harán dependiendo del comportamiento de que " "``None`` no se puede llamar." #: ../Doc/reference/datamodel.rst:3102 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:3108 #, fuzzy 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 asume que si el método no reflejado (como :" "meth:`__add__`) falla, la operación no es soportada, por lo cual el método " "reflejado no es llamado." #~ 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:type:`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 de caracteres 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 puede representar en una cadena de caracteres. " #~ "Python no tiene un tipo :c:type:`char`; en cambio, cada punto de código " #~ "en la cadena de caracteres se representa como un objeto de cadena de " #~ "caracteres con longitud ``1``. La función incorporada :func:`ord` " #~ "convierte un punto de código de su forma de cadena de caracteres a un " #~ "entero en el rango ``0 - 10FFFF``; la función :func:`chr` convierte un " #~ "entero en el rango ``0 - 10FFFF`` a la cadena de caracteres " #~ "correspondiente de longitud ``1``. :meth:`str.encode` se puede usar para " #~ "convertir un objeto de tipo :class:`str` a :class:`bytes` usando la " #~ "codificación de texto dada, y :meth:`bytes.decode` se puede usar para " #~ "lograr el caso inverso." #~ msgid "" #~ "If ``a`` is an instance of :class:`super`, then the binding ``super(B, " #~ "obj).m()`` searches ``obj.__class__.__mro__`` for the base class ``A`` " #~ "immediately preceding ``B`` and then invokes the descriptor with the " #~ "call: ``A.__dict__['m'].__get__(obj, obj.__class__)``." #~ msgstr "" #~ "Si ``a`` es una instancia de :class:`super`, entonces el enlace " #~ "``super(B, obj).m()`` busca ``obj.__class__.__mro__`` la clase base ``A`` " #~ "que precede inmediatamente ``B`` y luego invoca al descriptor con el " #~ "llamado: ``A.__dict__[‘m’].__get__(obj, obj.__class__)``." #~ msgid "" #~ "Any non-string iterable may be assigned to *__slots__*. Mappings may also " #~ "be used; however, in the future, special meaning may be assigned to the " #~ "values corresponding to each key." #~ msgstr "" #~ "Cualquier iterable sin cadena de caracteres puede ser asignado a " #~ "*__slots__*. Mapeos también pueden ser utilizados; sin embargo, en el " #~ "futuro, un significado especial puede ser asignado a los valores " #~ "correspondientes para cada llave." #~ msgid "" #~ "One can implement the generic class syntax as specified by :pep:`484` " #~ "(for example ``List[int]``) by defining a special method:" #~ msgstr "" #~ "Uno puede implementar la sintaxis de clase genérica como lo especifica :" #~ "pep:`484` (por ejemplo ``List[int]``) definiendo un método especial:" #~ msgid "" #~ "This method is looked up on the class object itself, and when defined in " #~ "the class body, this method is implicitly a class method. Note, this " #~ "mechanism is primarily reserved for use with static type hints, other " #~ "usage is discouraged." #~ msgstr "" #~ "Este método es buscado en el objeto de clase mismo, y cuando es definido " #~ "en el cuerpo de la clase, este método es un método de clase implícito. " #~ "Tome en cuenta que este mecanismo es ante todo reservado para su uso con " #~ "sugerencias de tipo (*type hints*), no se aconseja otro uso." #~ msgid "" #~ "Iterator objects also need to implement this method; they are required to " #~ "return themselves. For more information on iterator objects, see :ref:" #~ "`typeiter`." #~ msgstr "" #~ "Objetos iteradores también necesitan implementar este método; son " #~ "requeridos para retornarse a sí mismos. Para mayor información sobre " #~ "objetos iteradores, ver :ref:`typeiter`." #~ msgid "" #~ "If :meth:`__int__` is not defined then the built-in function :func:`int` " #~ "falls back to :meth:`__trunc__`." #~ msgstr "" #~ "Si :meth:`__int__` no es definido, entonces la función incorporada :func:" #~ "`int` regresa a :meth:`__trunc__`."