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!
This exercise is part of the course
Intermediate Object-Oriented Programming in Python
Exercise 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 sameserial_number
and validate that these objects are equal.
Hands-on interactive exercise
Have a go at this exercise by completing this sample 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(____ ____ ____)