Le Polymorphisme en Python

Introduction au Polymorphisme

Le polymorphisme est un concept fondamental de la programmation orientée objet qui permet à différentes classes de répondre différemment à la même interface. En Python, il existe deux types principaux de polymorphisme :

1. Polymorphisme au Runtime (Duck Typing)

Le polymorphisme au runtime en Python est basé sur le principe du "duck typing" : si un objet marche comme un canard et fait coin-coin comme un canard, alors c'est un canard. En d'autres termes, le type exact d'un objet importe moins que ses capacités.


# Exemple de polymorphisme au runtime
class Canard:
    def faire_son(self):
        return "Coin coin !"

class Chat:
    def faire_son(self):
        return "Miaou !"

class Chien:
    def faire_son(self):
        return "Wouf !"

def faire_parler_animal(animal):
    # Aucune vérification de type n'est nécessaire
    print(animal.faire_son())

# Les trois objets fonctionnent car ils ont la méthode faire_son()
canard = Canard()
chien = Chien()
chat = Chat()

faire_parler_animal(canard)  # Coin coin !
faire_parler_animal(chien)   # Wouf !
faire_parler_animal(chat)    # Miaou !

2. Polymorphisme au Compile-time (Typing)

Avec l'introduction du module typing en Python 3.5+, il est possible d'implémenter une forme de polymorphisme au compile-time. Cela permet de détecter les erreurs de type avant l'exécution du code.


from typing import Protocol, List

# Définition d'un protocole (interface)
class Animal(Protocol):
    def faire_son(self) -> str: ...

class Chien:
    def faire_son(self) -> str:
        return "Wouf !"

class Chat:
    def faire_son(self) -> str:
        return "Miaou !"

# Le type hint assure que seuls les objets conformes au protocole Animal sont acceptés
def faire_parler_animaux(animaux: List[Animal]) -> None:
    for animal in animaux:
        print(animal.faire_son())

# Utilisation avec vérification de type
animaux: List[Animal] = [Chien(), Chat()]
faire_parler_animaux(animaux)

Différences Clés entre Runtime et Compile-time

Aspect Runtime (Duck Typing) Compile-time (Typing)
Vérification Pendant l'exécution Avant l'exécution
Flexibilité Très flexible Plus strict
Sécurité Moins sûr Plus sûr
Performance Pas d'overhead Léger overhead

Avantages et Inconvénients

Runtime Polymorphism

Compile-time Polymorphism

Quand Utiliser Quel Type ?

Le choix entre runtime et compile-time dépend de vos besoins :

Utilisez le Runtime Polymorphism quand :

Utilisez le Compile-time Polymorphism quand :

Points Clés à Retenir

Prochaines Étapes

That's all folks