# Copyright (C) 2001-2018, Python Software Foundation # For licence information, see README file. # msgid "" msgstr "" "Project-Id-Version: Python 3\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2021-05-19 22:36+0200\n" "PO-Revision-Date: 2020-12-17 21:41+0100\n" "Last-Translator: Mathieu Dupuy \n" "Language-Team: FRENCH \n" "Language: fr\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "X-Generator: Poedit 2.3\n" #: howto/descriptor.rst:5 msgid "Descriptor HowTo Guide" msgstr "Guide pour l'utilisation des descripteurs" #: howto/descriptor.rst:0 msgid "Author" msgstr "Auteur" #: howto/descriptor.rst:7 msgid "Raymond Hettinger" msgstr "Raymond Hettinger" #: howto/descriptor.rst:0 msgid "Contact" msgstr "Contact" #: howto/descriptor.rst:8 msgid "" msgstr "" #: howto/descriptor.rst:11 msgid "Contents" msgstr "Sommaire" #: howto/descriptor.rst:13 msgid "" ":term:`Descriptors ` let objects customize attribute lookup, " "storage, and deletion." msgstr "" #: howto/descriptor.rst:16 msgid "This guide has four major sections:" msgstr "" #: howto/descriptor.rst:18 msgid "" "The \"primer\" gives a basic overview, moving gently from simple examples, " "adding one feature at a time. Start here if you're new to descriptors." msgstr "" #: howto/descriptor.rst:21 msgid "" "The second section shows a complete, practical descriptor example. If you " "already know the basics, start there." msgstr "" #: howto/descriptor.rst:24 msgid "" "The third section provides a more technical tutorial that goes into the " "detailed mechanics of how descriptors work. Most people don't need this " "level of detail." msgstr "" #: howto/descriptor.rst:28 msgid "" "The last section has pure Python equivalents for built-in descriptors that " "are written in C. Read this if you're curious about how functions turn into " "bound methods or about the implementation of common tools like :func:" "`classmethod`, :func:`staticmethod`, :func:`property`, and :term:`__slots__`." msgstr "" #: howto/descriptor.rst:36 msgid "Primer" msgstr "" #: howto/descriptor.rst:38 msgid "" "In this primer, we start with the most basic possible example and then we'll " "add new capabilities one by one." msgstr "" #: howto/descriptor.rst:43 msgid "Simple example: A descriptor that returns a constant" msgstr "" #: howto/descriptor.rst:45 msgid "" "The :class:`Ten` class is a descriptor that always returns the constant " "``10`` from its :meth:`__get__` method:" msgstr "" #: howto/descriptor.rst:54 msgid "" "To use the descriptor, it must be stored as a class variable in another " "class:" msgstr "" #: howto/descriptor.rst:62 msgid "" "An interactive session shows the difference between normal attribute lookup " "and descriptor lookup:" msgstr "" #: howto/descriptor.rst:73 msgid "" "In the ``a.x`` attribute lookup, the dot operator finds the key ``x`` and " "the value ``5`` in the class dictionary. In the ``a.y`` lookup, the dot " "operator finds a descriptor instance, recognized by its ``__get__`` method, " "and calls that method which returns ``10``." msgstr "" #: howto/descriptor.rst:78 msgid "" "Note that the value ``10`` is not stored in either the class dictionary or " "the instance dictionary. Instead, the value ``10`` is computed on demand." msgstr "" #: howto/descriptor.rst:81 msgid "" "This example shows how a simple descriptor works, but it isn't very useful. " "For retrieving constants, normal attribute lookup would be better." msgstr "" #: howto/descriptor.rst:84 msgid "" "In the next section, we'll create something more useful, a dynamic lookup." msgstr "" #: howto/descriptor.rst:88 msgid "Dynamic lookups" msgstr "" #: howto/descriptor.rst:90 msgid "" "Interesting descriptors typically run computations instead of returning " "constants:" msgstr "" #: howto/descriptor.rst:109 msgid "" "An interactive session shows that the lookup is dynamic — it computes " "different, updated answers each time::" msgstr "" #: howto/descriptor.rst:122 msgid "" "Besides showing how descriptors can run computations, this example also " "reveals the purpose of the parameters to :meth:`__get__`. The *self* " "parameter is *size*, an instance of *DirectorySize*. The *obj* parameter is " "either *g* or *s*, an instance of *Directory*. It is the *obj* parameter " "that lets the :meth:`__get__` method learn the target directory. The " "*objtype* parameter is the class *Directory*." msgstr "" #: howto/descriptor.rst:131 msgid "Managed attributes" msgstr "" #: howto/descriptor.rst:133 msgid "" "A popular use for descriptors is managing access to instance data. The " "descriptor is assigned to a public attribute in the class dictionary while " "the actual data is stored as a private attribute in the instance " "dictionary. The descriptor's :meth:`__get__` and :meth:`__set__` methods " "are triggered when the public attribute is accessed." msgstr "" #: howto/descriptor.rst:139 msgid "" "In the following example, *age* is the public attribute and *_age* is the " "private attribute. When the public attribute is accessed, the descriptor " "logs the lookup or update:" msgstr "" #: howto/descriptor.rst:172 msgid "" "An interactive session shows that all access to the managed attribute *age* " "is logged, but that the regular attribute *name* is not logged:" msgstr "" #: howto/descriptor.rst:206 msgid "" "One major issue with this example is that the private name *_age* is " "hardwired in the *LoggedAgeAccess* class. That means that each instance can " "only have one logged attribute and that its name is unchangeable. In the " "next example, we'll fix that problem." msgstr "" #: howto/descriptor.rst:213 msgid "Customized names" msgstr "" #: howto/descriptor.rst:215 msgid "" "When a class uses descriptors, it can inform each descriptor about which " "variable name was used." msgstr "" #: howto/descriptor.rst:218 msgid "" "In this example, the :class:`Person` class has two descriptor instances, " "*name* and *age*. When the :class:`Person` class is defined, it makes a " "callback to :meth:`__set_name__` in *LoggedAccess* so that the field names " "can be recorded, giving each descriptor its own *public_name* and " "*private_name*:" msgstr "" #: howto/descriptor.rst:256 msgid "" "An interactive session shows that the :class:`Person` class has called :meth:" "`__set_name__` so that the field names would be recorded. Here we call :" "func:`vars` to look up the descriptor without triggering it:" msgstr "" #: howto/descriptor.rst:267 msgid "The new class now logs access to both *name* and *age*:" msgstr "" #: howto/descriptor.rst:284 msgid "The two *Person* instances contain only the private names:" msgstr "" #: howto/descriptor.rst:295 msgid "Closing thoughts" msgstr "" #: howto/descriptor.rst:297 msgid "" "A :term:`descriptor` is what we call any object that defines :meth:" "`__get__`, :meth:`__set__`, or :meth:`__delete__`." msgstr "" #: howto/descriptor.rst:300 msgid "" "Optionally, descriptors can have a :meth:`__set_name__` method. This is " "only used in cases where a descriptor needs to know either the class where " "it was created or the name of class variable it was assigned to. (This " "method, if present, is called even if the class is not a descriptor.)" msgstr "" #: howto/descriptor.rst:305 msgid "" "Descriptors get invoked by the dot \"operator\" during attribute lookup. If " "a descriptor is accessed indirectly with ``vars(some_class)" "[descriptor_name]``, the descriptor instance is returned without invoking it." msgstr "" #: howto/descriptor.rst:309 msgid "" "Descriptors only work when used as class variables. When put in instances, " "they have no effect." msgstr "" #: howto/descriptor.rst:312 msgid "" "The main motivation for descriptors is to provide a hook allowing objects " "stored in class variables to control what happens during attribute lookup." msgstr "" #: howto/descriptor.rst:315 msgid "" "Traditionally, the calling class controls what happens during lookup. " "Descriptors invert that relationship and allow the data being looked-up to " "have a say in the matter." msgstr "" #: howto/descriptor.rst:319 msgid "" "Descriptors are used throughout the language. It is how functions turn into " "bound methods. Common tools like :func:`classmethod`, :func:" "`staticmethod`, :func:`property`, and :func:`functools.cached_property` are " "all implemented as descriptors." msgstr "" #: howto/descriptor.rst:326 msgid "Complete Practical Example" msgstr "" #: howto/descriptor.rst:328 msgid "" "In this example, we create a practical and powerful tool for locating " "notoriously hard to find data corruption bugs." msgstr "" #: howto/descriptor.rst:333 msgid "Validator class" msgstr "" #: howto/descriptor.rst:335 msgid "" "A validator is a descriptor for managed attribute access. Prior to storing " "any data, it verifies that the new value meets various type and range " "restrictions. If those restrictions aren't met, it raises an exception to " "prevent data corruption at its source." msgstr "" #: howto/descriptor.rst:340 msgid "" "This :class:`Validator` class is both an :term:`abstract base class` and a " "managed attribute descriptor:" msgstr "" #: howto/descriptor.rst:363 msgid "" "Custom validators need to inherit from :class:`Validator` and must supply a :" "meth:`validate` method to test various restrictions as needed." msgstr "" #: howto/descriptor.rst:368 msgid "Custom validators" msgstr "" #: howto/descriptor.rst:370 msgid "Here are three practical data validation utilities:" msgstr "" #: howto/descriptor.rst:372 msgid "" ":class:`OneOf` verifies that a value is one of a restricted set of options." msgstr "" #: howto/descriptor.rst:374 msgid "" ":class:`Number` verifies that a value is either an :class:`int` or :class:" "`float`. Optionally, it verifies that a value is between a given minimum or " "maximum." msgstr "" #: howto/descriptor.rst:378 msgid "" ":class:`String` verifies that a value is a :class:`str`. Optionally, it " "validates a given minimum or maximum length. It can validate a user-defined " "`predicate `_ " "as well." msgstr "" #: howto/descriptor.rst:437 msgid "Practical application" msgstr "" #: howto/descriptor.rst:439 msgid "Here's how the data validators can be used in a real class:" msgstr "" #: howto/descriptor.rst:454 msgid "The descriptors prevent invalid instances from being created:" msgstr "" #: howto/descriptor.rst:481 msgid "Technical Tutorial" msgstr "" #: howto/descriptor.rst:483 msgid "" "What follows is a more technical tutorial for the mechanics and details of " "how descriptors work." msgstr "" #: howto/descriptor.rst:488 msgid "Abstract" msgstr "Résumé" #: howto/descriptor.rst:490 msgid "" "Defines descriptors, summarizes the protocol, and shows how descriptors are " "called. Provides an example showing how object relational mappings work." msgstr "" #: howto/descriptor.rst:493 #, fuzzy msgid "" "Learning about descriptors not only provides access to a larger toolset, it " "creates a deeper understanding of how Python works." msgstr "" "L'apprentissage des descripteurs permet non seulement d'accéder à un " "ensemble d'outils plus vaste, mais aussi de mieux comprendre le " "fonctionnement de Python et d'apprécier l'élégance de sa conception." #: howto/descriptor.rst:498 #, fuzzy msgid "Definition and introduction" msgstr "Définition et introduction" #: howto/descriptor.rst:500 #, fuzzy msgid "" "In general, a descriptor is an attribute value that has one of the methods " "in the descriptor protocol. Those methods are :meth:`__get__`, :meth:" "`__set__`, and :meth:`__delete__`. If any of those methods are defined for " "an attribute, it is said to be a :term:`descriptor`." msgstr "" "En général, un descripteur est un attribut objet avec un \"comportement " "contraignant\", dont l'accès à l'attribut a été remplacé par des méthodes " "dans le protocole du descripteur. Ces méthodes sont : :meth:`__get__`, :" "meth:`__set__`, et :meth:`__delete__`. Si l'une de ces méthodes est définie " "pour un objet, il s'agit d'un descripteur." #: howto/descriptor.rst:505 #, fuzzy 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 method resolution order of ``type(a)``. 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." msgstr "" "Le comportement par défaut pour l'accès aux attributs consiste à obtenir, " "définir ou supprimer l'attribut du dictionnaire d'un objet. Par exemple, " "``a. x`` a une chaîne de recherche commençant par ``a. __dict__ ['x']``, " "puis ``type (a). __dict__ ['x']``, et continuant à travers les classes de " "base de ``type (a)`` À l'exclusion des sous-classes. Si la valeur recherchée " "est un objet définissant l'une des méthodes de descripteur, Python peut " "substituer le comportement par défaut et appeler à la place la méthode " "Descriptor. Lorsque cela se produit dans la chaîne de précédence dépend de " "quelles méthodes descripteur ont été définies." #: howto/descriptor.rst:514 #, fuzzy msgid "" "Descriptors are a powerful, general purpose protocol. They are the " "mechanism behind properties, methods, static methods, class methods, and :" "func:`super()`. They are used throughout Python itself. Descriptors " "simplify the underlying C code and offer a flexible set of new tools for " "everyday Python programs." msgstr "" "Les descripteurs sont un protocole puissant et à usage général. Ils sont le " "mécanisme derrière les propriétés, les méthodes, les méthodes statiques, les " "méthodes de classes et :func:`super()`. Ils sont utilisés dans tout Python " "lui-même pour implémenter les nouvelles classes de style introduites dans la " "version 2.2. Les descripteurs simplifient le code C sous-jacent et offrent " "un ensemble flexible de nouveaux outils pour les programmes Python " "quotidiens." #: howto/descriptor.rst:522 #, fuzzy msgid "Descriptor protocol" msgstr "Protocole descripteur" #: howto/descriptor.rst:524 msgid "``descr.__get__(self, obj, type=None) -> value``" msgstr "``descr.__get__(self, obj, type=None) -> value``" #: howto/descriptor.rst:526 msgid "``descr.__set__(self, obj, value) -> None``" msgstr "``descr.__set__(self, obj, value) -> None``" #: howto/descriptor.rst:528 msgid "``descr.__delete__(self, obj) -> None``" msgstr "``descr.__delete__(self, obj) -> None``" #: howto/descriptor.rst:530 msgid "" "That is all there is to it. Define any of these methods and an object is " "considered a descriptor and can override default behavior upon being looked " "up as an attribute." msgstr "" "C'est tout ce qu'il y a à faire. Définissez n'importe laquelle de ces " "méthodes et un objet est considéré comme un descripteur et peut remplacer le " "comportement par défaut lorsqu'il est recherché comme un attribut." #: howto/descriptor.rst:534 #, fuzzy msgid "" "If an object defines :meth:`__set__` or :meth:`__delete__`, it is considered " "a data descriptor. Descriptors that only define :meth:`__get__` are called " "non-data descriptors (they are often used for methods but other uses are " "possible)." msgstr "" "Si un objet définit :meth:`__set__` ou :meth:`__delete__`, il est considéré " "comme un descripteur de données. Les descripteurs qui ne définissent que :" "meth:`__get__` sont appelés descripteurs *non-data* (ils sont généralement " "utilisés pour des méthodes mais d'autres utilisations sont possibles)." #: howto/descriptor.rst:539 msgid "" "Data and non-data descriptors differ in how overrides are calculated with " "respect to entries in an instance's dictionary. If an instance's dictionary " "has an entry with the same name as a data descriptor, the data descriptor " "takes precedence. If an instance's dictionary has an entry with the same " "name as a non-data descriptor, the dictionary entry takes precedence." msgstr "" "Les descripteurs de données et les descripteurs *non-data* diffèrent dans la " "façon dont les dérogations sont calculées en ce qui concerne les entrées du " "dictionnaire d'une instance. Si le dictionnaire d'une instance comporte une " "entrée portant le même nom qu'un descripteur de données, le descripteur de " "données est prioritaire. Si le dictionnaire d'une instance comporte une " "entrée portant le même nom qu'un descripteur *non-data*, l'entrée du " "dictionnaire a la priorité." #: howto/descriptor.rst:545 msgid "" "To make a read-only data descriptor, define both :meth:`__get__` and :meth:" "`__set__` with the :meth:`__set__` raising an :exc:`AttributeError` when " "called. Defining the :meth:`__set__` method with an exception raising " "placeholder is enough to make it a data descriptor." msgstr "" "Pour faire un descripteur de données en lecture seule, définissez à la fois :" "meth:`__get__` et :meth:`__set__` avec :meth:`__set__` levant une erreur :" "exc:`AttributeError` quand il est appelé. Définir la méthode :meth:" "`__set__set__` avec une exception élevant le caractère générique est " "suffisant pour en faire un descripteur de données." #: howto/descriptor.rst:552 msgid "Overview of descriptor invocation" msgstr "" #: howto/descriptor.rst:554 #, fuzzy msgid "" "A descriptor can be called directly with ``desc.__get__(obj)`` or ``desc." "__get__(None, cls)``." msgstr "" "Un descripteur peut être appelé directement par son nom de méthode. Par " "exemple, ``d.__get__(obj)``." #: howto/descriptor.rst:557 msgid "" "But it is more common for a descriptor to be invoked automatically from " "attribute access." msgstr "" #: howto/descriptor.rst:560 msgid "" "The expression ``obj.x`` looks up the attribute ``x`` in the chain of " "namespaces for ``obj``. If the search finds a descriptor outside of the " "instance ``__dict__``, its :meth:`__get__` method is invoked according to " "the precedence rules listed below." msgstr "" #: howto/descriptor.rst:565 #, fuzzy msgid "" "The details of invocation depend on whether ``obj`` is an object, class, or " "instance of super." msgstr "" "Les détails de l'invocation dépendent du fait que ``obj`` est un objet ou " "une classe." #: howto/descriptor.rst:570 msgid "Invocation from an instance" msgstr "" #: howto/descriptor.rst:572 msgid "" "Instance lookup scans through a chain of namespaces giving data descriptors " "the highest priority, followed by instance variables, then non-data " "descriptors, then class variables, and lastly :meth:`__getattr__` if it is " "provided." msgstr "" #: howto/descriptor.rst:577 msgid "" "If a descriptor is found for ``a.x``, then it is invoked with: ``desc." "__get__(a, type(a))``." msgstr "" #: howto/descriptor.rst:580 msgid "" "The logic for a dotted lookup is in :meth:`object.__getattribute__`. Here " "is a pure Python equivalent:" msgstr "" #: howto/descriptor.rst:700 msgid "" "Interestingly, attribute lookup doesn't call :meth:`object.__getattribute__` " "directly. Instead, both the dot operator and the :func:`getattr` function " "perform attribute lookup by way of a helper function:" msgstr "" #: howto/descriptor.rst:747 msgid "" "So if :meth:`__getattr__` exists, it is called whenever :meth:" "`__getattribute__` raises :exc:`AttributeError` (either directly or in one " "of the descriptor calls)." msgstr "" #: howto/descriptor.rst:750 msgid "" "Also, if a user calls :meth:`object.__getattribute__` directly, the :meth:" "`__getattr__` hook is bypassed entirely." msgstr "" #: howto/descriptor.rst:755 #, fuzzy msgid "Invocation from a class" msgstr "Appelé depuis un Classe" #: howto/descriptor.rst:757 msgid "" "The logic for a dotted lookup such as ``A.x`` is in :meth:`type." "__getattribute__`. The steps are similar to those for :meth:`object." "__getattribute__` but the instance dictionary lookup is replaced by a search " "through the class's :term:`method resolution order`." msgstr "" #: howto/descriptor.rst:762 msgid "If a descriptor is found, it is invoked with ``desc.__get__(None, A)``." msgstr "" #: howto/descriptor.rst:764 msgid "" "The full C implementation can be found in :c:func:`type_getattro()` and :c:" "func:`_PyType_Lookup()` in :source:`Objects/typeobject.c`." msgstr "" #: howto/descriptor.rst:769 msgid "Invocation from super" msgstr "" #: howto/descriptor.rst:771 msgid "" "The logic for super's dotted lookup is in the :meth:`__getattribute__` " "method for object returned by :class:`super()`." msgstr "" #: howto/descriptor.rst:774 #, fuzzy msgid "" "A dotted lookup such as ``super(A, obj).m`` searches ``obj.__class__." "__mro__`` for the base class ``B`` immediately following ``A`` and then " "returns ``B.__dict__['m'].__get__(obj, A)``. If not a descriptor, ``m`` is " "returned unchanged." msgstr "" "L'objet renvoyé par ``super()`` a également une méthode personnalisée :meth:" "`__getattribute__` pour invoquer des descripteurs. La recherche d'attribut " "``super(B, obj).m`` recherche dans ``obj.__class__.__mro__`` la classe qui " "suit immédiatement B, appelons la A, et renvoie ``A.__dict__['m']." "__get__(obj, B)``. Si ce n'est pas un descripteur, ``m`` est renvoyé " "inchangé. S'il n'est pas dans le dictionnaire, la recherche de ``m`` revient " "à une recherche utilisant :meth:`object.__getattribute__`." #: howto/descriptor.rst:779 #, fuzzy msgid "" "The full C implementation can be found in :c:func:`super_getattro()` in :" "source:`Objects/typeobject.c`. A pure Python equivalent can be found in " "`Guido's Tutorial `_." msgstr "" "Les détails d'implémentation sont dans :c:func:`super_getattro()` dans :" "source:`Objects/typeobject.c` et un équivalent Python pur peut être trouvé " "dans `Guido's Tutorial`_." #: howto/descriptor.rst:786 msgid "Summary of invocation logic" msgstr "" #: howto/descriptor.rst:788 msgid "" "The mechanism for descriptors is embedded in the :meth:`__getattribute__()` " "methods for :class:`object`, :class:`type`, and :func:`super`." msgstr "" #: howto/descriptor.rst:791 msgid "The important points to remember are:" msgstr "Les points importants à retenir sont :" #: howto/descriptor.rst:793 #, fuzzy msgid "Descriptors are invoked by the :meth:`__getattribute__` method." msgstr "les descripteurs sont appelés par la méthode :meth:`__getattribute__`" #: howto/descriptor.rst:795 msgid "" "Classes inherit this machinery from :class:`object`, :class:`type`, or :func:" "`super`." msgstr "" #: howto/descriptor.rst:798 #, fuzzy msgid "" "Overriding :meth:`__getattribute__` prevents automatic descriptor calls " "because all the descriptor logic is in that method." msgstr "" "redéfinir :meth:`__getattribute____` empêche les appels automatiques de " "descripteurs" #: howto/descriptor.rst:801 #, fuzzy msgid "" ":meth:`object.__getattribute__` and :meth:`type.__getattribute__` make " "different calls to :meth:`__get__`. The first includes the instance and may " "include the class. The second puts in ``None`` for the instance and always " "includes the class." msgstr "" ":meth:`objet.__getattribute__` et :meth:`type.__getattribute__` font " "différents appels à :meth:`__get__`." #: howto/descriptor.rst:806 #, fuzzy msgid "Data descriptors always override instance dictionaries." msgstr "" "les descripteurs de données remplacent toujours les dictionnaires " "d'instances." #: howto/descriptor.rst:808 #, fuzzy msgid "Non-data descriptors may be overridden by instance dictionaries." msgstr "" "les descripteurs *non-data* peuvent être remplacés par des dictionnaires " "d'instance." #: howto/descriptor.rst:812 msgid "Automatic name notification" msgstr "" #: howto/descriptor.rst:814 msgid "" "Sometimes it is desirable for a descriptor to know what class variable name " "it was assigned to. When a new class is created, the :class:`type` " "metaclass scans the dictionary of the new class. If any of the entries are " "descriptors and if they define :meth:`__set_name__`, that method is called " "with two arguments. The *owner* is the class where the descriptor is used, " "and the *name* is the class variable the descriptor was assigned to." msgstr "" #: howto/descriptor.rst:821 #, fuzzy msgid "" "The implementation details are in :c:func:`type_new()` and :c:func:" "`set_names()` in :source:`Objects/typeobject.c`." msgstr "" "Les détails d'implémentation sont dans :c:func:`super_getattro()` dans :" "source:`Objects/typeobject.c` et un équivalent Python pur peut être trouvé " "dans `Guido's Tutorial`_." #: howto/descriptor.rst:824 msgid "" "Since the update logic is in :meth:`type.__new__`, notifications only take " "place at the time of class creation. If descriptors are added to the class " "afterwards, :meth:`__set_name__` will need to be called manually." msgstr "" #: howto/descriptor.rst:830 msgid "ORM example" msgstr "" #: howto/descriptor.rst:832 msgid "" "The following code is simplified skeleton showing how data descriptors could " "be used to implement an `object relational mapping `_." msgstr "" #: howto/descriptor.rst:836 msgid "" "The essential idea is that the data is stored in an external database. The " "Python instances only hold keys to the database's tables. Descriptors take " "care of lookups or updates:" msgstr "" #: howto/descriptor.rst:855 msgid "" "We can use the :class:`Field` class to define `models `_ that describe the schema for each table in a " "database:" msgstr "" #: howto/descriptor.rst:880 msgid "To use the models, first connect to the database::" msgstr "" #: howto/descriptor.rst:885 msgid "" "An interactive session shows how data is retrieved from the database and how " "it can be updated:" msgstr "" #: howto/descriptor.rst:930 msgid "Pure Python Equivalents" msgstr "" #: howto/descriptor.rst:932 #, fuzzy msgid "" "The descriptor protocol is simple and offers exciting possibilities. " "Several use cases are so common that they have been prepackaged into built-" "in tools. Properties, bound methods, static methods, class methods, and \\_" "\\_slots\\_\\_ are all based on the descriptor protocol." msgstr "" "Le protocole est simple et offre des possibilités passionnantes. Plusieurs " "cas d'utilisation sont si courants qu'ils ont été regroupés en appels de " "fonction individuels. Les propriétés, les méthodes liées, les méthodes " "statiques et les méthodes de classe sont toutes basées sur le protocole du " "descripteur." #: howto/descriptor.rst:939 msgid "Properties" msgstr "Propriétés" #: howto/descriptor.rst:941 #, fuzzy msgid "" "Calling :func:`property` is a succinct way of building a data descriptor " "that triggers a function call upon access to an attribute. Its signature " "is::" msgstr "" "Appeler :func:`property` est une façon succincte de construire un " "descripteur de données qui déclenche des appels de fonction lors de l'accès " "à un attribut. Sa signature est ::" #: howto/descriptor.rst:946 #, fuzzy msgid "" "The documentation shows a typical use to define a managed attribute ``x``:" msgstr "" "La documentation montre une utilisation typique pour définir un attribut " "géré ``x`` ::" #: howto/descriptor.rst:970 #, fuzzy msgid "" "To see how :func:`property` is implemented in terms of the descriptor " "protocol, here is a pure Python equivalent:" msgstr "" "Pour voir comment :func:`property` est implémenté dans le protocole du " "descripteur, voici un un équivalent Python pur ::" #: howto/descriptor.rst:1063 msgid "" "The :func:`property` builtin helps whenever a user interface has granted " "attribute access and then subsequent changes require the intervention of a " "method." msgstr "" "La fonction native :func:`property` aide chaque fois qu'une interface " "utilisateur a accordé l'accès à un attribut et que des modifications " "ultérieures nécessitent l'intervention d'une méthode." #: howto/descriptor.rst:1067 #, fuzzy msgid "" "For instance, a spreadsheet class may grant access to a cell value through " "``Cell('b10').value``. Subsequent improvements to the program require the " "cell to be recalculated on every access; however, the programmer does not " "want to affect existing client code accessing the attribute directly. The " "solution is to wrap access to the value attribute in a property data " "descriptor:" msgstr "" "Par exemple, une classe de tableur peut donner accès à une valeur de cellule " "via ``Cell('b10').value``. Les améliorations ultérieures du programme " "exigent que la cellule soit recalculée à chaque accès ; cependant, le " "programmeur ne veut pas affecter le code client existant accédant " "directement à l'attribut. La solution consiste à envelopper l'accès à " "l'attribut de valeur dans un descripteur de données de propriété ::" #: howto/descriptor.rst:1084 msgid "" "Either the built-in :func:`property` or our :func:`Property` equivalent " "would work in this example." msgstr "" #: howto/descriptor.rst:1089 #, fuzzy msgid "Functions and methods" msgstr "Fonctions et méthodes" #: howto/descriptor.rst:1091 msgid "" "Python's object oriented features are built upon a function based " "environment. Using non-data descriptors, the two are merged seamlessly." msgstr "" "Les fonctionnalités orientées objet de Python sont construites sur un " "environnement basé sur des fonctions. À l'aide de descripteurs *non-data*, " "les deux sont fusionnés de façon transparente." #: howto/descriptor.rst:1094 #, fuzzy msgid "" "Functions stored in class dictionaries get turned into methods when invoked. " "Methods only differ from regular functions in that the object instance is " "prepended to the other arguments. By convention, the instance is called " "*self* but could be called *this* or any other variable name." msgstr "" "Les dictionnaires de classes stockent les méthodes sous forme de fonctions. " "Dans une définition de classe, les méthodes sont écrites en utilisant :" "keyword:`def` ou :keyword:`lambda`, les outils habituels pour créer des " "fonctions. Les méthodes ne diffèrent des fonctions régulières que par le " "fait que le premier argument est réservé à l'instance de l'objet. Par " "convention Python, la référence de l'instance est appelée *self* mais peut " "être appelée *this* ou tout autre nom de variable." #: howto/descriptor.rst:1099 msgid "" "Methods can be created manually with :class:`types.MethodType` which is " "roughly equivalent to:" msgstr "" #: howto/descriptor.rst:1116 #, fuzzy msgid "" "To support automatic creation of methods, functions include the :meth:" "`__get__` method for binding methods during attribute access. This means " "that functions are non-data descriptors that return bound methods during " "dotted lookup from an instance. Here's how it works:" msgstr "" "Pour prendre en charge les appels de méthodes, les fonctions incluent la " "méthode :meth:`__get__` pour lier les méthodes pendant l'accès aux " "attributs. Cela signifie que toutes les fonctions sont des descripteurs " "*non-data* qui renvoient des méthodes liées lorsqu'elles sont appelées " "depuis un objet. En Python pur, il fonctionne comme ceci ::" #: howto/descriptor.rst:1132 #, fuzzy msgid "" "Running the following class in the interpreter shows how the function " "descriptor works in practice:" msgstr "" "L'exécution de l'interpréteur montre comment le descripteur de fonction se " "comporte dans la pratique ::" #: howto/descriptor.rst:1141 msgid "" "The function has a :term:`qualified name` attribute to support introspection:" msgstr "" #: howto/descriptor.rst:1148 msgid "" "Accessing the function through the class dictionary does not invoke :meth:" "`__get__`. Instead, it just returns the underlying function object::" msgstr "" #: howto/descriptor.rst:1154 msgid "" "Dotted access from a class calls :meth:`__get__` which just returns the " "underlying function unchanged::" msgstr "" #: howto/descriptor.rst:1160 msgid "" "The interesting behavior occurs during dotted access from an instance. The " "dotted lookup calls :meth:`__get__` which returns a bound method object::" msgstr "" #: howto/descriptor.rst:1167 msgid "" "Internally, the bound method stores the underlying function and the bound " "instance::" msgstr "" #: howto/descriptor.rst:1176 msgid "" "If you have ever wondered where *self* comes from in regular methods or " "where *cls* comes from in class methods, this is it!" msgstr "" #: howto/descriptor.rst:1181 #, fuzzy msgid "Kinds of methods" msgstr "Fonctions et méthodes" #: howto/descriptor.rst:1183 msgid "" "Non-data descriptors provide a simple mechanism for variations on the usual " "patterns of binding functions into methods." msgstr "" "Les descripteurs *non-data* fournissent un mécanisme simple pour les " "variations des patrons habituels des fonctions de liaison dans les méthodes." #: howto/descriptor.rst:1186 #, fuzzy msgid "" "To recap, functions have a :meth:`__get__` method so that they can be " "converted to a method when accessed as attributes. The non-data descriptor " "transforms an ``obj.f(*args)`` call into ``f(obj, *args)``. Calling ``cls." "f(*args)`` becomes ``f(*args)``." msgstr "" "Pour résumer, les fonctions ont une méthode :meth:`__get__` pour qu'elles " "puissent être converties en méthode lorsqu'on y accède comme attributs. Le " "descripteur *non-data* transforme un appel ``obj.f(*args)``en ``f(obj, " "*args)``. Appeler ``klass.f(*args)`` devient ``f(*args)``." #: howto/descriptor.rst:1191 msgid "This chart summarizes the binding and its two most useful variants:" msgstr "" "Ce tableau résume le lien (*binding*) et ses deux variantes les plus " "utiles ::" #: howto/descriptor.rst:1194 msgid "Transformation" msgstr "Transformation" #: howto/descriptor.rst:1194 #, fuzzy msgid "Called from an object" msgstr "Appelé depuis un Objet" #: howto/descriptor.rst:1194 #, fuzzy msgid "Called from a class" msgstr "Appelé depuis un Classe" #: howto/descriptor.rst:1197 msgid "function" msgstr "fonction" #: howto/descriptor.rst:1197 msgid "f(obj, \\*args)" msgstr "f(obj, \\*args)" #: howto/descriptor.rst:1199 msgid "f(\\*args)" msgstr "f(\\*args)" #: howto/descriptor.rst:1199 msgid "staticmethod" msgstr "méthode statique" #: howto/descriptor.rst:1201 msgid "classmethod" msgstr "méthode de classe" #: howto/descriptor.rst:1201 msgid "f(type(obj), \\*args)" msgstr "f(type(obj), \\*args)" #: howto/descriptor.rst:1201 msgid "f(cls, \\*args)" msgstr "f(cls, \\*args)" #: howto/descriptor.rst:1206 #, fuzzy msgid "Static methods" msgstr "méthode statique" #: howto/descriptor.rst:1208 msgid "" "Static methods return the underlying function without changes. Calling " "either ``c.f`` or ``C.f`` is the equivalent of a direct lookup into ``object." "__getattribute__(c, \"f\")`` or ``object.__getattribute__(C, \"f\")``. As a " "result, the function becomes identically accessible from either an object or " "a class." msgstr "" "Les méthodes statiques renvoient la fonction sous-jacente sans " "modifications. Appeler ``c.f`` ou ``C.f`` est l'équivalent d'une recherche " "directe dans ``objet.__getattribute__(c, \"f\")`` ou ``objet." "__getattribute__(C, \"f\")``. Par conséquent, la fonction devient accessible " "de manière identique à partir d'un objet ou d'une classe." #: howto/descriptor.rst:1214 msgid "" "Good candidates for static methods are methods that do not reference the " "``self`` variable." msgstr "" "Les bonnes candidates pour être méthode statique sont des méthodes qui ne " "font pas référence à la variable ``self``." #: howto/descriptor.rst:1217 msgid "" "For instance, a statistics package may include a container class for " "experimental data. The class provides normal methods for computing the " "average, mean, median, and other descriptive statistics that depend on the " "data. However, there may be useful functions which are conceptually related " "but do not depend on the data. For instance, ``erf(x)`` is handy conversion " "routine that comes up in statistical work but does not directly depend on a " "particular dataset. It can be called either from an object or the class: " "``s.erf(1.5) --> .9332`` or ``Sample.erf(1.5) --> .9332``." msgstr "" "Par exemple, un paquet traitant de statistiques peut inclure une classe qui " "est un conteneur pour des données expérimentales. La classe fournit les " "méthodes normales pour calculer la moyenne, la moyenne, la médiane et " "d'autres statistiques descriptives qui dépendent des données. Cependant, il " "peut y avoir des fonctions utiles qui sont conceptuellement liées mais qui " "ne dépendent pas des données. Par exemple, ``erf(x)`` est une routine de " "conversion pratique qui apparaît dans le travail statistique mais qui ne " "dépend pas directement d'un ensemble de données particulier. Elle peut être " "appelée à partir d'un objet ou de la classe : ``s.erf(1.5) --> .9332``` ou " "``Sample.erf(1.5) --> .9332``." #: howto/descriptor.rst:1226 #, fuzzy msgid "" "Since static methods return the underlying function with no changes, the " "example calls are unexciting:" msgstr "" "Depuis que les méthodes statiques renvoient la fonction sous-jacente sans " "changement, les exemples d’appels ne sont pas excitants ::" #: howto/descriptor.rst:1243 #, fuzzy msgid "" "Using the non-data descriptor protocol, a pure Python version of :func:" "`staticmethod` would look like this:" msgstr "" "En utilisant le protocole de descripteur *non-data*, une version Python pure " "de :func:`staticmethod` ressemblerait à ceci ::" #: howto/descriptor.rst:1275 #, fuzzy msgid "Class methods" msgstr "méthode de classe" #: howto/descriptor.rst:1277 #, fuzzy msgid "" "Unlike static methods, class methods prepend the class reference to the " "argument list before calling the function. This format is the same for " "whether the caller is an object or a class:" msgstr "" "Contrairement aux méthodes statiques, les méthodes de classe préchargent la " "référence de classe dans la liste d'arguments avant d'appeler la fonction. " "Ce format est le même que l'appelant soit un objet ou une classe ::" #: howto/descriptor.rst:1295 #, fuzzy msgid "" "This behavior is useful whenever the method only needs to have a class " "reference and does not rely on data stored in a specific instance. One use " "for class methods is to create alternate class constructors. For example, " "the classmethod :func:`dict.fromkeys` creates a new dictionary from a list " "of keys. The pure Python equivalent is:" msgstr "" "Ce comportement est utile lorsque la fonction n'a besoin que d'une référence " "de classe et ne se soucie pas des données sous-jacentes. Une des " "utilisations des méthodes de classe est de créer d'autres constructeurs de " "classe. En Python 2.3, la méthode de classe :func:`dict.fromkeys` crée un " "nouveau dictionnaire à partir d'une liste de clés. L'équivalent Python pur " "est ::" #: howto/descriptor.rst:1312 #, fuzzy msgid "Now a new dictionary of unique keys can be constructed like this:" msgstr "" "Maintenant un nouveau dictionnaire de clés uniques peut être construit comme " "ceci ::" #: howto/descriptor.rst:1322 #, fuzzy msgid "" "Using the non-data descriptor protocol, a pure Python version of :func:" "`classmethod` would look like this:" msgstr "" "En utilisant le protocole de descripteur *non-data*, une version Python pure " "de :func:`classmethod` ressemblerait à ceci ::" #: howto/descriptor.rst:1371 msgid "" "The code path for ``hasattr(type(self.f), '__get__')`` was added in Python " "3.9 and makes it possible for :func:`classmethod` to support chained " "decorators. For example, a classmethod and property could be chained " "together:" msgstr "" #: howto/descriptor.rst:1391 msgid "Member objects and __slots__" msgstr "" #: howto/descriptor.rst:1393 msgid "" "When a class defines ``__slots__``, it replaces instance dictionaries with a " "fixed-length array of slot values. From a user point of view that has " "several effects:" msgstr "" #: howto/descriptor.rst:1397 msgid "" "1. Provides immediate detection of bugs due to misspelled attribute " "assignments. Only attribute names specified in ``__slots__`` are allowed:" msgstr "" #: howto/descriptor.rst:1413 msgid "" "2. Helps create immutable objects where descriptors manage access to private " "attributes stored in ``__slots__``:" msgstr "" #: howto/descriptor.rst:1448 msgid "" "3. Saves memory. On a 64-bit Linux build, an instance with two attributes " "takes 48 bytes with ``__slots__`` and 152 bytes without. This `flyweight " "design pattern `_ likely " "only matters when a large number of instances are going to be created." msgstr "" #: howto/descriptor.rst:1453 msgid "" "4. Blocks tools like :func:`functools.cached_property` which require an " "instance dictionary to function correctly:" msgstr "" #: howto/descriptor.rst:1475 msgid "" "It is not possible to create an exact drop-in pure Python version of " "``__slots__`` because it requires direct access to C structures and control " "over object memory allocation. However, we can build a mostly faithful " "simulation where the actual C structure for slots is emulated by a private " "``_slotvalues`` list. Reads and writes to that private structure are " "managed by member descriptors:" msgstr "" #: howto/descriptor.rst:1518 msgid "" "The :meth:`type.__new__` method takes care of adding member objects to class " "variables:" msgstr "" #: howto/descriptor.rst:1534 msgid "" "The :meth:`object.__new__` method takes care of creating instances that have " "slots instead of an instance dictionary. Here is a rough simulation in pure " "Python:" msgstr "" #: howto/descriptor.rst:1569 msgid "" "To use the simulation in a real class, just inherit from :class:`Object` and " "set the :term:`metaclass` to :class:`Type`:" msgstr "" #: howto/descriptor.rst:1583 msgid "" "At this point, the metaclass has loaded member objects for *x* and *y*::" msgstr "" #: howto/descriptor.rst:1604 msgid "" "When instances are created, they have a ``slot_values`` list where the " "attributes are stored:" msgstr "" #: howto/descriptor.rst:1616 msgid "Misspelled or unassigned attributes will raise an exception:" msgstr "" #~ msgid "" #~ "Defines descriptors, summarizes the protocol, and shows how descriptors " #~ "are called. Examines a custom descriptor and several built-in Python " #~ "descriptors including functions, properties, static methods, and class " #~ "methods. Shows how each works by giving a pure Python equivalent and a " #~ "sample application." #~ msgstr "" #~ "Définit les descripteurs, résume le protocole et montre comment les " #~ "descripteurs sont appelés. Examine un descripteur personnalisé et " #~ "plusieurs descripteurs Python intégrés, y compris les fonctions, les " #~ "propriétés, les méthodes statiques et les méthodes de classe. Montre " #~ "comment chacun fonctionne en donnant un équivalent Python pur et un " #~ "exemple d'application." #~ msgid "Invoking Descriptors" #~ msgstr "Invocation des descripteurs" #~ msgid "" #~ "Alternatively, it is more common for a descriptor to be invoked " #~ "automatically upon attribute access. For example, ``obj.d`` looks up " #~ "``d`` in the dictionary of ``obj``. If ``d`` defines the method :meth:" #~ "`__get__`, then ``d.__get__(obj)`` is invoked according to the precedence " #~ "rules listed below." #~ msgstr "" #~ "Alternativement, il est plus courant qu'un descripteur soit invoqué " #~ "automatiquement lors de l'accès aux attributs. Par exemple, ``obj.d`` " #~ "recherche ``d`` dans le dictionnaire de ``obj.d``. Si ``d`` définit la " #~ "méthode :meth:`__get__`, alors ``d.__get__(obj)`` est invoqué selon les " #~ "règles de priorité énumérées ci-dessous." #~ msgid "" #~ "For objects, the machinery is in :meth:`object.__getattribute__` which " #~ "transforms ``b.x`` into ``type(b).__dict__['x'].__get__(b, type(b))``. " #~ "The implementation works through a precedence chain that gives data " #~ "descriptors priority over instance variables, instance variables priority " #~ "over non-data descriptors, and assigns lowest priority to :meth:" #~ "`__getattr__` if provided. The full C implementation can be found in :c:" #~ "func:`PyObject_GenericGetAttr()` in :source:`Objects/object.c`." #~ msgstr "" #~ "Pour les objets, la machinerie est dans :meth:`object.__getattribute__` " #~ "qui transforme ``b.x`` en ``type(b).__dict__['x'].__get__(b, type(b)]``. " #~ "L'implémentation fonctionne à travers une chaîne de priorité qui donne la " #~ "priorité aux descripteurs de données sur les variables d'instance, la " #~ "priorité aux variables d'instance sur les descripteurs *non-data*, et " #~ "attribue la priorité la plus faible à :meth:`__getattr__` si fourni. " #~ "L'implémentation complète en C peut être trouvée dans :c:func:" #~ "`PyObject_GenericGetAttr()` dans :source:`Objects/object.c`." #~ msgid "" #~ "For classes, the machinery is in :meth:`type.__getattribute__` which " #~ "transforms ``B.x`` into ``B.__dict__['x'].__get__(None, B)``. In pure " #~ "Python, it looks like::" #~ msgstr "" #~ "Pour les classes, la machinerie est dans :meth:`type.__getattribute__` " #~ "qui transforme ``B.x`` en ``B.__dict__['x'].__get__(None, B)``. En " #~ "Python pur, cela ressemble à ::" #~ msgid "" #~ "The details above show that the mechanism for descriptors is embedded in " #~ "the :meth:`__getattribute__()` methods for :class:`object`, :class:" #~ "`type`, and :func:`super`. Classes inherit this machinery when they " #~ "derive from :class:`object` or if they have a meta-class providing " #~ "similar functionality. Likewise, classes can turn-off descriptor " #~ "invocation by overriding :meth:`__getattribute__()`." #~ msgstr "" #~ "Les détails ci-dessus montrent que le mécanisme des descripteurs est " #~ "intégré dans les méthodes :meth:`__getattribute__()` pour :class:" #~ "`object`, :class:`type` et :func:`super`. Les classes héritent de cette " #~ "machinerie lorsqu'elles dérivent de :class:`object` ou si elles ont une " #~ "méta-classe fournissant des fonctionnalités similaires. De même, les " #~ "classes peuvent désactiver l'appel de descripteurs en remplaçant :meth:" #~ "`__getattribute__()`." #~ msgid "Descriptor Example" #~ msgstr "Exemple de descripteur" #~ msgid "" #~ "The following code creates a class whose objects are data descriptors " #~ "which print a message for each get or set. Overriding :meth:" #~ "`__getattribute__` is alternate approach that could do this for every " #~ "attribute. However, this descriptor is useful for monitoring just a few " #~ "chosen attributes::" #~ msgstr "" #~ "Le code suivant crée une classe dont les objets sont des descripteurs de " #~ "données qui affichent un message pour chaque lecture ou écriture. " #~ "Redéfinir :meth:`__getattribute__` est une approche alternative qui " #~ "pourrait le faire pour chaque attribut. Cependant, ce descripteur n'est " #~ "utile que pour le suivi de quelques attributs choisis ::" #~ msgid "Static Methods and Class Methods" #~ msgstr "Méthodes statiques et méthodes de classe"