CommencerCommencer gratuitement

Overloading the == operator

Python's built-in operators are handy, especially when comparing instances of a class. When building classes, magic methods can be used to change the functionality of these operators. Here, you'll overload the == operator to determine if two instances of a Computer are equal.

Cet exercice fait partie du cours

Intermediate Object-Oriented Programming in Python

Afficher le cours

Instructions

  • Define a magic method to overload the == operator.
  • Compare the device_id attributes of self and other in the magic method to determine if the two instances are equal.
  • Check if pre_upgrade_computer and post_upgrade_computer are equal, and print the result.

Exercice interactif pratique

Essayez cet exercice en complétant cet exemple de code.

class Computer:
  def __init__(self, device_id, storage):
    self.device_id = device_id
    self.storage = storage
  
  # Overload the == operator using a magic method
  def ____(self, other):
    # Return a boolean based on the value of device_id
    ____ self.____ == other.____

pre_upgrade_computer = Computer("Y391Hky6", 256)
post_upgrade_computer = Computer("Y391Hky6", 1024)

# Create two instances of Computer, compare using ==
print(____ == ____)
Modifier et exécuter le code