IniziaInizia gratis

Overloading equality

When comparing two objects of a custom class using ==, Python by default compares just the memory chunks that the objects point to, not the data contained in the objects. To override this behavior, the class can implement a special method, which accepts two arguments, the objects to be compared, and returns True or False. This method will be implicitly called when two objects are compared.

The BankAccount class from the previous chapter is available for you in the script.py. It has two attributes, balance and number, and a withdraw() method. Two bank accounts with the same balance are not necessarily the same account, but a bank account usually has an account number, and two accounts with the same account number should be considered the same.

Questo esercizio fa parte del corso

Introduction to Object-Oriented Programming in Python

Visualizza il corso

Istruzioni dell'esercizio

  • Modify the __init__() method to accept a new argument called number and initialize a new number attribute.
  • Define a method to compare if the number attribute of two objects are equal.

Esercizio pratico interattivo

Prova a risolvere questo esercizio completando il codice di esempio.

class BankAccount:
  # Modify to initialize a number attribute
  def __init__(self, ____, balance=0):
    self.balance = balance
    ____
      
  def withdraw(self, amount):
    self.balance -= amount 
    
  # Define __eq__ that returns True if the number attributes are equal 
  def ____(____, ____):
    return ____.number == ____.____   

# Create accounts and compare them       
acct1 = BankAccount(123, 1000)
acct2 = BankAccount(123, 1000)
acct3 = BankAccount(456, 1000)
print(acct1 == acct2)
print(acct1 == acct3)
    
Modifica ed esegui il codice