issue172:python
Différences
Ci-dessous, les différences entre deux révisions de la page.
Prochaine révision | Révision précédente | ||
issue172:python [2021/08/30 09:39] – créée auntiee | issue172:python [2021/08/31 17:28] (Version actuelle) – auntiee | ||
---|---|---|---|
Ligne 1: | Ligne 1: | ||
- | Well, I’ve made it. 10 full years worth of Python articles in the series. Actually, it’s been over 10 years in calendar time, but as far as articles are concerned, it’s 10 years worth. Thank you, dear readers, for hanging in with me for so long. | + | **Well, I’ve made it. 10 full years worth of Python articles in the series. Actually, it’s been over 10 years in calendar time, but as far as articles are concerned, it’s 10 years worth. Thank you, dear readers, for hanging in with me for so long. |
Way back in the dawn of time, when rainbows were in black-and-white, | Way back in the dawn of time, when rainbows were in black-and-white, | ||
Ligne 6: | Ligne 6: | ||
Run the clock forward, and I eventually added Visual Basic (both DOS and Windows versions) to my toolkit of programming languages. Visual Basic also had a similar user defined type, but it was called a structure. You would define the structure like this: | Run the clock forward, and I eventually added Visual Basic (both DOS and Windows versions) to my toolkit of programming languages. Visual Basic also had a similar user defined type, but it was called a structure. You would define the structure like this: | ||
+ | |||
+ | Public Structure TbookRec | ||
+ | Public Title as String | ||
+ | Public Author as String | ||
+ | Public ISBN as String | ||
+ | Public Price as Decimal | ||
+ | End Structure | ||
+ | |||
+ | Dim myBookRec as TbookRec | ||
+ | TbookRec.Title = “I Robot” | ||
+ | TbookRec.Author = “Isaac Asimov”** | ||
+ | |||
+ | Eh bien, je l'ai fait. 10 années complètes d' | ||
+ | |||
+ | À l'aube des temps, lorsque les arcs-en-ciel étaient en noir et blanc et que nous devions regarder la télévision à la bougie parce que l' | ||
+ | |||
+ | Et ainsi de suite. Nous pouvions utiliser un tableau d' | ||
+ | |||
+ | En avance rapide, j'ai fini par ajouter Visual Basic (versions DOS et Windows) à ma panoplie de langages de programmation. Visual Basic avait également un type similaire défini par l' | ||
Public Structure TbookRec | Public Structure TbookRec | ||
Ligne 18: | Ligne 37: | ||
TbookRec.Author = “Isaac Asimov” | TbookRec.Author = “Isaac Asimov” | ||
- | And on and on. When I came to Python (it was back before 3.0 came out), there wasn’t a convenient data structure like these. Having done a tonne of database work in my previous projects, I was somewhat at a loss. How could such a cool programming language like Python not have a structure like other languages. | + | |
+ | **And on and on. When I came to Python (it was back before 3.0 came out), there wasn’t a convenient data structure like these. Having done a tonne of database work in my previous projects, I was somewhat at a loss. How could such a cool programming language like Python not have a structure like other languages. | ||
This month, we will be looking at dataclasses, | This month, we will be looking at dataclasses, | ||
Ligne 40: | Ligne 60: | ||
QtyOnHand : int | QtyOnHand : int | ||
- | Notice I added a field, QtyOnHand in our example. This makes it a bit more realistic but still minimal and a good way to demo the dataclass. At this point, we need to define an empty list to hold the record structures, and then create our in memory “database” by creating various “books” that will be in our imaginary store inventory. | + | Notice I added a field, QtyOnHand in our example. This makes it a bit more realistic but still minimal and a good way to demo the dataclass. At this point, we need to define an empty list to hold the record structures, and then create our in memory “database” by creating various “books” that will be in our imaginary store inventory.** |
- | myRecs = [] | + | Et ainsi de suite. Lorsque j'en suis arrivé à Python (c' |
+ | |||
+ | Ce mois-ci, nous allons nous pencher sur les classes de données, un élément qui a été introduit en Python 3.7 : | ||
+ | ••Les tuples nommés ont été introduits en Python 2.6 mais les tuples nommés, comme tous les tuples, sont immuables. | ||
+ | ••Les classes de données sont faciles à utiliser, faciles à lire et sont mutables. | ||
+ | |||
+ | Nous allons créer une démo très simple (et irréaliste) de point de vente d'une petite librairie. Voici comment commencer à travailler avec les classes de données. | ||
+ | |||
+ | Tout d' | ||
+ | |||
+ | from dataclasses import dataclass | ||
+ | |||
+ | Ensuite, vous devez ajouter un décorateur pour commencer à définir votre classe. La dataclass ressemble à presque toutes les autres classes, mais les fonctions __init__ et __repr__, ainsi que quelques autres fonctions de base, sont automatiquement créées pour vous. Nous allons reprendre la structure de la présentation ci-dessus : | ||
+ | |||
+ | @dataclass | ||
+ | classe TbookRec : | ||
+ | Titre : str | ||
+ | Auteur : str | ||
+ | ISBN : str | ||
+ | Prix : float | ||
+ | QtyOnHand : int | ||
+ | |||
+ | Remarquez que j'ai ajouté un champ, QtyOnHand dans notre exemple. Cela rend l' | ||
+ | |||
+ | |||
+ | **myRecs = [] | ||
To make things a bit cleaner, we’ll create a function to do all the “database” entries at one time. We load the data into the dataclass and then append it to the myRecs list and “rinse and repeat”. I’ll show the creation of only three records, but in the demo file from the repository, I create five records. The main thing I want to show here is that inserting data into a dataclass is simple. So simple in fact, that, assuming you maintain the order of variables, you don’t have to include the field names. If you don’t keep the order of the variables, you must include the field names (top right). | To make things a bit cleaner, we’ll create a function to do all the “database” entries at one time. We load the data into the dataclass and then append it to the myRecs list and “rinse and repeat”. I’ll show the creation of only three records, but in the demo file from the repository, I create five records. The main thing I want to show here is that inserting data into a dataclass is simple. So simple in fact, that, assuming you maintain the order of variables, you don’t have to include the field names. If you don’t keep the order of the variables, you must include the field names (top right). | ||
Ligne 58: | Ligne 103: | ||
Now another simple function to search by book title. Remember, I’m not trying to cover any typos, capitalization errors, etc. Just trying to make it simple to show the ease of dealing with searching the data (top right). | Now another simple function to search by book title. Remember, I’m not trying to cover any typos, capitalization errors, etc. Just trying to make it simple to show the ease of dealing with searching the data (top right). | ||
- | And it’s output is like this… | + | And it’s output is like this…** |
- | Enter Book Title -> I Robot | + | mesRecs = [] |
+ | |||
+ | Pour rendre les choses un peu plus propres, nous allons créer une fonction pour effectuer toutes les entrées dans la « base de données » en une seule fois. Nous chargeons les données dans la classe de données, puis nous les ajoutons à la liste myRecs et nous « rinçons et répétons ». Je vais montrer la création de seulement trois enregistrements, | ||
+ | |||
+ | Vous devriez donc voir qu'il est non seulement facile d' | ||
+ | |||
+ | Créons maintenant une fonction pour rechercher le jeu d' | ||
+ | |||
+ | Le résultat de la fonction de recherche par auteur ressemble à ceci : | ||
+ | |||
+ | Title: The Hitchiker' | ||
+ | |||
+ | Title: The Restaurant at the End of the Universe | ||
+ | |||
+ | Maintenant, une autre fonction simple pour une recherche par titre de livre. Rappelez-vous, | ||
+ | |||
+ | Et la sortie est comme ceci : | ||
+ | |||
+ | |||
+ | **Enter Book Title -> I Robot | ||
Title: I Robot | Title: I Robot | ||
... | ... | ||
Ligne 77: | Ligne 141: | ||
While not grammatically correct, here is the output. (As my sainted mother would say, “Do as I say do, not as I do do.”) | While not grammatically correct, here is the output. (As my sainted mother would say, “Do as I say do, not as I do do.”) | ||
+ | Enter Title ->I Robot | ||
+ | There are now 1 book(s) left in stock.** | ||
+ | Enter Book Title -> I Robot | ||
+ | Title: I Robot | ||
+ | ... | ||
+ | Enter Book Title -> Raise The Titanic | ||
+ | Title: Raise The Titanic | ||
+ | Nous allons créer une autre fonction de recherche très simple, cette fois-ci par ISBN (en bas à droite). | ||
+ | Le résultat est le suivant : | ||
+ | |||
+ | Enter ISBN -> 978-1529034530 | ||
+ | Title: The Restaurant at the End of the Universe | ||
+ | |||
+ | Maintenant que nous avons abordé les fonctions de recherche simples, il est logique d' | ||
+ | |||
+ | Bien que ce ne soit pas grammaticalement correct, voici le résultat. (Comme le dirait ma sainte mère, « Fais ce que je dis, ne fais pas ce que je fais »). | ||
Enter Title ->I Robot | Enter Title ->I Robot | ||
- | There are now 1 book(s) left in stock. | + | There are now 1 book(s) left in stock. |
- | And just to make sure, you can call for a refresh of the book data, the list of books shows that we did in fact decrement the quantity-on-hand for that book by calling the book function. | + | **And just to make sure, you can call for a refresh of the book data, the list of books shows that we did in fact decrement the quantity-on-hand for that book by calling the book function. |
Number of Unique Books: 5 | Number of Unique Books: 5 | ||
Ligne 101: | Ligne 182: | ||
You’ll be able to find the code for this month’s article at my github repository at https:// | You’ll be able to find the code for this month’s article at my github repository at https:// | ||
- | Until next time, as always; stay safe, healthy, positive and creative! | + | Until next time, as always; stay safe, healthy, positive and creative!** |
+ | |||
+ | Et pour être sûr, vous pouvez demander un rafraîchissement des données du livre, la liste des livres montre que nous avons en fait décrémenté la quantité disponible de ce livre en appelant la fonction livre. | ||
+ | |||
+ | Number of Unique Books: 5 | ||
+ | Title: I Robot Author: Isaac Asimov | ||
+ | Title: The Gentle Giants of Ganymede | ||
+ | Title: Raise The Titanic | ||
+ | Title: The Hitchiker' | ||
+ | Title: The Restaurant at the End of the Universe | ||
+ | |||
+ | Enfin, créons une boucle « travail » qui offre un menu simple pour gérer les appels aux différentes fonctions (en haut à droite). | ||
+ | |||
+ | J' | ||
+ | |||
+ | Si vous voulez en savoir plus sur les classes de données Python, vous pouvez consulter la très bonne présentation et le guide de Geir Arne Hjelle sur Real Python (https:// | ||
+ | |||
+ | Vous pourrez trouver le code de l' | ||
+ | |||
+ | Jusqu' | ||
+ | |||
+ | |||
+ | // p 20 encart en haut à droite // | ||
+ | **And then to put data into the record, we would do something like this.** | ||
+ | Et ensuite, pour mettre les données dans l' | ||
+ | |||
+ | // p 21 encart en haut à droite // | ||
+ | **Now that we have that taken care of, we can create some simple functions to interact with the user. The first | ||
+ | one will show a list of all the items in the “database” including the quantity on hand. Let’s call it “books” to keep | ||
+ | things simple.** | ||
+ | Maintenant que nous nous en sommes occupés, nous pouvons créer quelques fonctions simples pour interagir avec l' | ||
+ | **When the function books is called, the output will look like this…** | ||
+ | Quand la fonction books est appelée, la sortie ressemble à ceci : |
issue172/python.1630309170.txt.gz · Dernière modification : 2021/08/30 09:39 de auntiee