Comparação com herança e representação em string

Introdução à programação orientada a objetos em Python

George Boorman

Curriculum Manager, DataCamp

Comparando objetos de classes diferentes

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

    def __eq__(self, other):
        # Retorna True se os objetos tiverem os mesmos atributos
        # e forem do mesmo tipo
        return (self.acc_id == other.acc_id) and (self.name == other.name)\
            and (type(self) == type(other))
Introdução à programação orientada a objetos em Python

Comparando objetos com herança

 

 

 

                               

    E se um objeto herdar da classe do outro?

Introdução à programação orientada a objetos em Python

Contas corrente e poupança

SavingsAccount herdando de BankAccount

Introdução à programação orientada a objetos em Python

__eq__ em classes pai/filho

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

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

    # Define __eq__ que retorna True 
    # se os atributos number forem iguais 
    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

    # Define __eq__ que retorna True 
    # se os atributos number forem iguais 
    def __eq__(self, other):
        print("SavingsAccount __eq__() called")
        return self.number == other.number 
Introdução à programação orientada a objetos em Python

Comparando objetos pai e filho

ba = BankAccount(123, 10000)
sa = SavingsAccount(456, 2000, 0.05)
# Compare os dois objetos
ba == sa
SavingsAccount __eq__() called
False
sa == ba
SavingsAccount __eq__() called
False
Introdução à programação orientada a objetos em Python

Imprimindo um objeto

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]
Introdução à programação orientada a objetos em Python

__str__()

  • print(obj), str(obj)
print(np.array([1,2,3]))
[1 2 3]
str(np.array([1,2,3]))
'[1 2 3]'
  • informal, para usuário final
  • representação em string

__repr__()

  • repr(obj), impressão no console
repr(np.array([1,2,3]))
'array([1,2,3])'
np.array([1,2,3])
array([1, 2, 3])
  • formal, para desenvolvedor
  • representação reprodutível
  • fallback de print()
Introdução à programação orientada a objetos em Python

Implementação: repr

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

    def __repr__(self):

# Repare nas aspas '...' ao redor de name return f"Customer('{self.name}', {self.balance})"
cust = Customer("Maryam Azar", 3000) # Chama __repr__() implicitamente cust
Customer('Maryam Azar', 3000)
Introdução à programação orientada a objetos em Python

Implementação: 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)

# Chama __str__() implicitamente
print(cust)
Customer:
  name: Maryam Azar
  balance: 3000
Introdução à programação orientada a objetos em Python

Vamos praticar!

Introdução à programação orientada a objetos em Python

Preparing Video For Download...