Hi there ๐ I'm a New York City based web developer documenting my journey with React, React Native, and Python for all to see. Please follow my dev.to profile or my twitter for updates and feel free to reach out if you have questions. Thanks for your support!
Today we follow up on yesterday's post about overloading the built-in print method. This time, we're overloading ==
, >
, and <
operators.
It's always useful to be able to compare things, and it's somewhat natural that two instances of the same class might be able to be compared. But the built-in functionality for those operators is to compare either numbers or strings, not classes.
Let's say we are a car dealership and we want a program that can help us figure out quickly what the value of different cars is. We want to just quickly compare them.
Obviously if I create a Car
class and then compare two instances of that class, we'll just get an error. Like so:
class Car:
def __init__(self, make, model, price):
self.make = make
self.model = model
self.price = price
mustang = Car("Ford", "Mustang", 60000)
camaro = Car("Chevy", "Camaro", 50000)
print(mustang > camaro)
# Will print the following:
# ERROR!
# Traceback (most recent call last):
# File "<string>", line 12, in <module>
# TypeError: '>' not supported between instances of 'Car' and # 'Car'
>
So to create method on this class that overrides the built-in functionality so that we can compare these Car
class instances, let's use the built-in eq
, gt
, and lt
methods.
class Car:
#...
def __eq__(self, target):
if (self.price == target.price):
return True
else:
return False
def __gt__(self, target):
if (self.__eq__(target) == True):
return False
elif (self.price > target.price):
return True
else:
False
def __lt__(self. target):
if (self.__eq__(target) == True):
return False
elif (self.__gt__(target) == True):
return False
else:
return True
By using the built-in eq
, gt
, and lt
keywords we can tap into this functionality and define our own behavior for ==
, >
, and <
.
So now if we compare two cars:
mustang = Car("Ford", "Mustang", 60000)
camaro = Car("Chevy", "Camaro", 50000)
print(mustang > camaro)
print(mustang < camaro)
print(mustang == camaro)
We get the result:
True
False
False
If you like projects like this and want to stay up to date with more, check out my Twitter @stonestwebdev, I follow back! See you tomorrow for another project.
Top comments (0)