Programmation orientée objet en Python
Alex Yarosh
Content Quality Analyst @ DataCamp

class BankAccount:
def __init__(self, balance):
self.balance = balance
def withdraw(self, amount):
self.balance -=amount
# Classe vide héritée de BankAccount
class SavingsAccount(BankAccount):
pass
class SavingsAccount(BankAccount): # Constructeur spécifique pour SavingsAccount avec un paramètre supplémentaire def __init__(self, balance, interest_rate):# Appeler le constructeur parent en utilisant ClassName.__init__() BankAccount.__init__(self, balance) # <--- self est un SavingsAccount mais aussi un BankAccount# Ajouter plus de fonctionnalités self.interest_rate = interest_rate
Parent.__init__(self, args...)# Construire l'objet en utilisant le nouveau constructeur
acct = SavingsAccount(1000, 0.03)
acct.interest_rate
0.03
class SavingsAccount(BankAccount):
def __init__(self, balance, interest_rate):
BankAccount.__init__(self, balance)
self.interest_rate = interest_rate
# Nouvelle fonctionnalité
def compute_interest(self, n_periods = 1):
return self.balance * ( (1 + self.interest_rate) ** n_periods - 1)

class CheckingAccount(BankAccount):def __init__(self, balance, limit): BankAccount.__init__(self, balance) self.limit = limitdef deposit(self, amount): self.balance += amountdef withdraw(self, amount, fee=0):if fee <= self.limit: BankAccount.withdraw(self, amount + fee) else: BankAccount.withdraw(self, amount + self.limit)
Parent.method(self, args...) pour appeler une méthode de la classe parentecheck_acct = CheckingAccount(1000, 25)
# Appellera withdraw de CheckingAccount
check_acct.withdraw(200)
# Appellera withdraw de CheckingAccount
check_acct.withdraw(200, fee=15)
bank_acct = BankAccount(1000)
# Appellera withdraw de BankAccount
bank_acct.withdraw(200)
# Provoquera une erreur
bank_acct.withdraw(200, fee=15)
TypeError: withdraw() a reçu un argument
inattendu 'fee'
Programmation orientée objet en Python