URL: https://linuxfr.org/users/killruana/journaux/python-ellipsis-operator Title: python: ellipsis operator (...) Authors: jtremesay Date: 2022年09月15日T20:29:57+02:00 License: CC By-SA Tags: python, ellipsis et operator Score: 29 J'ai découvert l'ellipsis operator de [python](https://fr.wikipedia.org/wiki/Python_(langage)) (`...`). Dans le contexte où je l'utilise, c'est équivalent à `pass`, autrement dit ne rien faire. C'est utilisé principalement pour quand python attend qu'un bloc syntaxique soit rempli (corps d'une fonction, d'une boucle, ...), mais qu'on a vraiment rien à y faire. Je trouve que ça permet de faire des interfaces plus élégantes. ```python from abc import ABC, abstractmethod class CarElementVisitor(ABC): @abstractmethod def visitBody(self, element): ... @abstractmethod def visitEngine(self, element): ... @abstractmethod def visitWheel(self, element): ... @abstractmethod def visitCar(self, element): ... ``` plutôt que ```python from abc import ABC, abstractmethod class CarElementVisitor(ABC): @abstractmethod def visitBody(self, element): raise NotImplementedError @abstractmethod def visitEngine(self, element): raise NotImplementedError @abstractmethod def visitWheel(self, element): raise NotImplementedError @abstractmethod def visitCar(self, element): raise NotImplementedError ``` La perte de l'exception n'est pas un problème car elle n'est de toute façon jamais lancé, [`abc`](https://docs.python.org/3/library/abc.html) (Abstract Base Classes, module python ajoutant les notions de [classes abstraites](https://fr.wikipedia.org/wiki/Classe_abstraite) et d'[interfaces](https://fr.wikipedia.org/wiki/Interface_de_programmation) s'occupant d'en lancer une automatiquement: ``` $ ipython Python 3.10.6 (main, Aug 3 2022, 17:39:45) [GCC 12.1.1 20220730] Type 'copyright', 'credits' or 'license' for more information IPython 8.4.0 -- An enhanced Interactive Python. Type '?' for help. In [1]: from abc import ABC, abstractmethod ...: ...: class CarElementVisitor(ABC): ...: @abstractmethod ...: def visitBody(self, element): ...: ... ...: ...: @abstractmethod ...: def visitEngine(self, element): ...: ... ...: ...: @abstractmethod ...: def visitWheel(self, element): ...: ... ...: ...: @abstractmethod ...: def visitCar(self, element): ...: ... ...: In [2]: CarElementVisitor() --------------------------------------------------------------------------- TypeError Traceback (most recent call last) Input In [2], in () ----> 1 CarElementVisitor() TypeError: Can't instantiate abstract class CarElementVisitor with abstract methods visitBody, visitCar, visitEngine, visitWheel ```

AltStyle によって変換されたページ (->オリジナル) /