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.
This exercise is part of the course
Intermediate Object-Oriented Programming in Python
Exercise instructions
- Define a magic method to overload the
==
operator. - Compare the
device_id
attributes ofself
andother
in the magic method to determine if the two instances are equal. - Check if
pre_upgrade_computer
andpost_upgrade_computer
are equal, and print the result.
Hands-on interactive exercise
Have a go at this exercise by completing this sample 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(____ == ____)