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!
Este exercício faz parte do curso
Intermediate Object-Oriented Programming in Python
Instruções do exercício
- Define a magic method to overload the
==operator used to compare two objects. - Use the
serial_numberattribute to determine if two objects of the Computer class are equal. - Create two objects of type
Computerwith the sameserial_numberand validate that these objects are equal.
Exercício interativo prático
Experimente este exercício completando este código de exemplo.
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(____ ____ ____)