Héritage de classes

Introduction à la programmation orientée objet en Python

George Boorman

Curriculum Manager, DataCamp

Réutilisation du code

 

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

 

  • Les progiciels conviennent aux fonctions fixes
  • La POO est idéale pour personnaliser des fonctions

logos de plusieurs progiciels Python

Introduction à la programmation orientée objet en Python

Réutilisation du code

 

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

 

2. DRY : Don't Repeat Yourself

divers éléments d'interface graphique

Introduction à la programmation orientée objet en Python

Réutilisation du code

 

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

 

2. DRY : Don't Repeat Yourself

n'utilisez pas divers éléments d'interface graphique

Introduction à la programmation orientée objet en Python

Héritage

 

$$\Large{\text{Fonctionnalité nouvelle classe = fonctionnalité ancienne classe + extra}}$$

Introduction à la programmation orientée objet en Python

Exemple de hiérarchie

Classe BankAccount

Introduction à la programmation orientée objet en Python

Exemple de hiérarchie

SavingsAccount hérite de BankAccount

Introduction à la programmation orientée objet en Python

Exemple de hiérarchie

CheckingAccount hérite aussi de BankAccount

Introduction à la programmation orientée objet en Python

Exemple de hiérarchie

CheckingAccount a une méthode withdraw modifiée

Introduction à la programmation orientée objet en Python

Mettre en œuvre l'héritage de classes

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 en ajoute d'autres
Introduction à la programmation orientée objet en Python

La classe enfant possède toutes les données de la parente

# Constructor inherited from BankAccount
savings_acct = SavingsAccount(1000)
type(savings_acct)
__main__.SavingsAccount
# Attribute inherited from BankAccount
savings_acct.balance
1000
# Method inherited from BankAccount
savings_acct.withdraw(300)
Introduction à la programmation orientée objet en Python

Héritage : relation « est-un »

Un SavingsAccount est un BankAccount

(avec des fonctions particulières, au besoin)

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...