Comparaison avec héritage et représentation texte

Introduction à la programmation orientée objet en Python

George Boorman

Curriculum Manager, DataCamp

Comparer des objets de classes différentes

class Customer:
    def __init__(self, acc_id, name):
        self.acc_id, self.name = acc_id, name

    def __eq__(self, other):
        # Renvoie True si les objets ont les mêmes attributs
        # et sont du même type
        return (self.acc_id == other.acc_id) and (self.name == other.name)\
            and (type(self) == type(other))
Introduction à la programmation orientée objet en Python

Comparer avec l’héritage

 

 

 

                               

    Et si un objet héritait de la classe de l’autre ?

Introduction à la programmation orientée objet en Python

Comptes courant et épargne

SavingsAccount héritant de BankAccount

Introduction à la programmation orientée objet en Python

__eq__ dans les classes parent/enfant

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

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

    # Définir __eq__ qui renvoie True 
    # si les attributs number sont égaux 
    def __eq__(self, other):
        print("BankAccount __eq__() called")
        return self.number == other.number 
class SavingsAccount(BankAccount):
    def __init__(self, number, balance, interest_rate):
        BankAccount.__init__(self, number,
                             balance)
          self.interest_rate = interest_rate

    # Définir __eq__ qui renvoie True 
    # si les attributs number sont égaux 
    def __eq__(self, other):
        print("SavingsAccount __eq__() called")
        return self.number == other.number 
Introduction à la programmation orientée objet en Python

Comparer objet parent et enfant

ba = BankAccount(123, 10000)
sa = SavingsAccount(456, 2000, 0.05)
# Comparer les deux objets
ba == sa
SavingsAccount __eq__() called
False
sa == ba
SavingsAccount __eq__() called
False
Introduction à la programmation orientée objet en Python

Afficher un objet

class Customer:
    def __init__(self, name, balance):
        self.name, self.balance = name, balance 

cust = Customer("Maryam Azar", 3000)
print(cust)
<__main__.Customer at 0x1f8598e2240>




a_list = [1,2,3]
print(a_list)
[1, 2, 3]
Introduction à la programmation orientée objet en Python

__str__()

  • print(obj), str(obj)
print(np.array([1,2,3]))
[1 2 3]
str(np.array([1,2,3]))
'[1 2 3]'
  • informel, pour l’utilisateur final
  • représentation en string

__repr__()

  • repr(obj), affichage en console
repr(np.array([1,2,3]))
'array([1,2,3])'
np.array([1,2,3])
array([1, 2, 3])
  • formel, pour le développeur
  • représentation reproduisible
  • repli pour print()
Introduction à la programmation orientée objet en Python

Implémentation : repr

class Customer:
    def __init__(self, name, balance):
        self.name = name
        self.balance = balance 

    def __repr__(self):

# Remarquez les '...' autour de name return f"Customer('{self.name}', {self.balance})"
cust = Customer("Maryam Azar", 3000) # Appelle implicitement __repr__() cust
Customer('Maryam Azar', 3000)
Introduction à la programmation orientée objet en Python

Implémentation : str

class Customer:
    def __init__(self, name, balance):
        self.name = name
        self.balance = balance
    def __str__(self):
        cust_str = f"""
        Customer:
            name: {self.name}
            balance: {self.balance}
            """
        return cust_str
cust = Customer("Maryam Azar", 3000)

# Appelle implicitement __str__()
print(cust)
Customer:
  name: Maryam Azar
  balance: 3000
Introduction à la programmation orientée objet en Python

Passons à la pratique !

Introduction à la programmation orientée objet en Python

Preparing Video For Download...