CommencerCommencer gratuitement

Overloading ==

Overloading allows for the functionality of built-in operators be customized using magic methods. In this example, you'll overload the == comparison operator for a Computer class, using the serial number for each device. Have at it!

Cet exercice fait partie du cours

Intermediate Object-Oriented Programming in Python

Afficher le cours

Instructions

  • Define a magic method to overload the == operator used to compare two objects.
  • Use the serial_number attribute to determine if two objects of the Computer class are equal.
  • Create two objects of type Computer with the same serial_number and validate that these objects are equal.

Exercice interactif pratique

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

class Computer:
  def __init__(self, serial_number):
    self.serial_number = serial_number
  
  # Overload the == operator using a magic method
  def ____(self, ____):
    # Define equality using serial_number
    ____ self.____ == other.____

# Validate two Computers with the same serial_number are equal
first_computer = Computer("81023762")
second_computer = ____("81023762")
print(____ ____ ____)
Modifier et exécuter le code