Operators Overloading In Python- Part 2

Python operators overloading are used to apply or perform mathematical calculations on the objects (instances) created from the class. You can also perform comparisons on these objects. Let’s see in this article how you can perform both of them on the objects.

1. Mathematics Operators Overloading

In the previous article, we’ve discovered some of the mathematical operators overloading, such as adding, subtracting, multiplying, and more. Still, we didn’t learn all of them since there is a lot to be learned in one tutorial so let’s dive into more of them in this article. We will start with how you can get the remainder of the division:

#Creating the class
class Book:
    
    #Initaiting the method
    def __init__(self, price):
        self.price = price
    
    #Calculate the power of the prices
    def __pow__(self, other):
        return self.price ** other.price

#Creating the objects
b1 = Book(3)
b2 = Book(6)

#Printing the power of the two books
print(b2 ** b1)

You can see that we’ve used the “__pow__” magic function for calculating the power of the two values. The two asterisks “**” are used for calculating the power value. Sometimes when you divide a number, you will get something called a reminder, and you can calculate that using the magic function:

#Creating the class
class Book:
    
    #Initaiting the method
    def __init__(self, price):
        self.price = price
    
    #Calculate the modulo of the prices
    def __mod__(self, other):
        return self.price % other.price

#Creating the objects
b1 = Book(3)
b2 = Book(7)

#Printing the modulo of the two books
print(b2 % b1)

You can see that we’ve used the “__mod__” to calculate the modulo of the second book divided on the first book, which will give one as a result. Let’s see another magic function:

#Creating the class
class Book:
    
    #Initaiting the method
    def __init__(self, price):
        self.price = price
    
    #Calculate the floor division of the prices
    def __floordiv__(self, other):
        return self.price // other.price

#Creating the objects
b1 = Book(3)
b2 = Book(7)

#Printing the floor division of the two books
print(b2 // b1)

As you saw previously, floor division is considered a regular division operation, but it returns the most significant possible integer. We could achieve this by using the “__floordiv__” function.

2. Comparison Operators Overloading 

Magic functions support the mathematical operations and the comparison operations, making it easy to evaluate conditions as you do in a usual python code. Let’s see how we implement it real example:

#Creating the class
class Computer:
    
    #Initaiting the method
    def __init__(self, price, quantity):
        self.price = price
        self.quantity = quantity

    #Less than operator  
    def __lt__(self, other):
        self_computer = (self.price * self.quantity)
        other_computer = (other.price * other.quantity)
        return self_computer < other_computer

#Creating the objects   
MacBook = Computer(1199, 21)
Asus = Computer(1361, 8)

#Compare the prices
print(MacBook < Asus)

Before you copy and paste the code to try it, let me explain first what it means because it seems a little bit confusing. Let’s consider a store with two types of computers. One is a MacBook which costs $1199 and has 21 of them, and the other computer type is Asus at $1361 but only has 8 of them.

This store wants to know which one will generate more revenue, so we created a comparison by implementing the “__lt__” magic functions, which stand for less than.

Inside this function, we have created two variables, and every variable will calculate the total price of the whole items of every computer type multiply it by its price.

The function will letter return the comparison between the first total price. If it is less than the second total price, it will return True. Otherwise, it will return False.

Later, we create two objects representing the two computers type, and you need to set the price of every item and the quantity of this computer type available in the store.

Finally, print the comparison result that will give you a False at the end, which means that MacBook computers will generate more revenue than the Asus computers. Let’s try to use the If statement to make it looks better than the previous example:

#Creating the class
class Computer:
    
    #Initaiting the method
    def __init__(self, price, quantity):
        self.price = price
        self.quantity = quantity

    #Less than operator  
    def __lt__(self, other):
        self_computer = (self.price * self.quantity)
        other_computer = (other.price * other.quantity)
        return self_computer < other_computer

#Creating the objects   
MacBook = Computer(1199, 21)
Asus = Computer(1361, 4)

#Compare the prices
if MacBook < Asus:
    print("MacBook is generating more revenue")
else:
    print("Asus is generating less revenue")

It will tell you that MacBook is generating more revenue. This is obvious since the quantity is much more than the Asus, although the price is a little bit less. Let’s see another comparison operator overloading:

#Creating the class
class Computer:
    
    #Initaiting the method
    def __init__(self, price, quantity):
        self.price = price
        self.quantity = quantity

    #Less than or equal operator  
    def __le__(self, other):
        self_computer = (self.price * self.quantity)
        other_computer = (other.price * other.quantity)
        return self_computer <= other_computer

#Creating the objects   
MacBook = Computer(1199, 21)
Asus = Computer(1361, 4)

#Compare the prices
print(MacBook <= Asus)

We’ve used the “__le__” magic function, which stands for less than or equal. The final result is False since the first item, MacBook, will generate more revenue than the Asus computers. There are many other magic functions, and let’s see more of them:

#Creating the class
class Computer:
    
    #Initaiting the method
    def __init__(self, price, quantity):
        self.price = price
        self.quantity = quantity

    #Greater than operator  
    def __gt__(self, other):
        self_computer = (self.price * self.quantity)
        other_computer = (other.price * other.quantity)
        return self_computer > other_computer

#Creating the objects   
MacBook = Computer(1199, 21)
Asus = Computer(1361, 4)

#Compare the prices
print(MacBook > Asus)

The result will be True since the MacBook has more revenue than Asus, and the function used in the previous example, “__gt__” stands for greater than. We can use another function similar to it:

#Creating the class
class Computer:
    
    #Initaiting the method
    def __init__(self, price, quantity):
        self.price = price
        self.quantity = quantity

    #Greater than or equal operator  
    def __ge__(self, other):
        self_computer = (self.price * self.quantity)
        other_computer = (other.price * other.quantity)
        return self_computer >= other_computer

#Creating the objects   
MacBook = Computer(1199, 21)
Asus = Computer(1361, 4)

#Compare the prices
print(MacBook >= Asus)

The function “__ge__” is greater than or equal, and it will print the same result as the previous example. Two other functions are left in this part, which is the first one “__eq__” magic function:

#Creating the class
class Computer:
    
    #Initaiting the method
    def __init__(self, price, quantity):
        self.price = price
        self.quantity = quantity

    #Equal to operator  
    def __eq__(self, other):
        self_computer = (self.price * self.quantity)
        other_computer = (other.price * other.quantity)
        return self_computer == other_computer

#Creating the objects   
MacBook = Computer(1199, 21)
Asus = Computer(1361, 4)

#Compare the prices
print(MacBook == Asus)

The magic function “__eq__” stands equal to, which will give you the False in the final result. Let’s see the last one:

#Creating the class
class Computer:
    
    #Initaiting the method
    def __init__(self, price, quantity):
        self.price = price
        self.quantity = quantity

    #Not equal to operator  
    def __ne__(self, other):
        self_computer = (self.price * self.quantity)
        other_computer = (other.price * other.quantity)
        return self_computer != other_computer

#Creating the objects   
MacBook = Computer(1199, 21)
Asus = Computer(1361, 4)

#Compare the prices
print(MacBook != Asus)

The result will be True since the value is not the same and the function “__ne__” is not equal.

Conclusion

Thanks for reading! Python developer has created many other operators overloading. This two-series article has discussed some of the most useful ones you may need in your python code in the future. Still, you can explore them if you want to.

Scroll to Top