Héritage de classes

Introduction à la programmation orientée objet en Python

George Boorman

Curriculum Manager, DataCamp

Réutilisation de code

 

1. Quelqu’un l’a déjà fait

 

  • Les packages offrent des fonctions fixes
  • La POO permet de personnaliser les fonctions

logos de plusieurs packages Python

Introduction à la programmation orientée objet en Python

Réutilisation de code

 

1. Quelqu’un l’a déjà fait

 

2. DRY : Don’t Repeat Yourself

divers éléments d’interface

Introduction à la programmation orientée objet en Python

Réutilisation de code

 

1. Quelqu’un l’a déjà fait

 

2. DRY : Don’t Repeat Yourself

n’utilisez pas divers éléments d’interface

Introduction à la programmation orientée objet en Python

Héritage

 

$$\Large{\text{Nouvelle classe = Ancienne classe + extra}}$$

Introduction à la programmation orientée objet en Python

Hiérarchie d’exemple

Classe BankAccount

Introduction à la programmation orientée objet en Python

Hiérarchie d’exemple

SavingsAccount héritant de BankAccount

Introduction à la programmation orientée objet en Python

Hiérarchie d’exemple

CheckingAccount héritant aussi de BankAccount

Introduction à la programmation orientée objet en Python

Hiérarchie d’exemple

CheckingAccount a une méthode withdraw modifiée

Introduction à la programmation orientée objet en Python

Implémenter l’héritage de classe

class BankAccount:
    def __init__(self, balance):
       self.balance = balance

    def withdraw(self, amount):
        self.balance -= amount


# Class inheriting from BankAccount class SavingsAccount(BankAccount): pass
  • BankAccount : classe parente dont on étend/hérite la fonctionnalité
  • SavingsAccount : classe enfant/sous-classe qui hérite et ajoute des fonctions
Introduction à la programmation orientée objet en Python

La classe enfant a toutes les données parentes

# Constructeur hérité de BankAccount
savings_acct = SavingsAccount(1000)
type(savings_acct)
__main__.SavingsAccount
# Attribut hérité de BankAccount
savings_acct.balance
1000
# Méthode héritée de BankAccount
savings_acct.withdraw(300)
Introduction à la programmation orientée objet en Python

Héritage : relation « est-un »

Un SavingsAccount est un BankAccount

(éventuellement avec des fonctions spéciales)

savings_acct = SavingsAccount(1000)
isinstance(savings_acct, SavingsAccount)
True
isinstance(savings_acct, BankAccount)
True

 

 

acct = BankAccount(500)
isinstance(acct, SavingsAccount)
False
isinstance(acct, BankAccount)
True
Introduction à la programmation orientée objet en Python

Passons à la pratique !

Introduction à la programmation orientée objet en Python

Preparing Video For Download...