Day #77 - Operator Overloading in Python

Day #77 - Operator Overloading in Python

Β·

4 min read

Introduction

Welcome to my 77th blog post on the Python journey. On day 77, I learned about a cool feature of Python that allows you to redefine the behavior of the operators. This is called Operator overloading in Python. Let's dive into more details of Operator Overloading in Python.

So let's get started......

What is Operator Overloading in Python?

  • It allows developers to redefine the behavior of mathematical and comparison operators for custom data types.

  • Here we can use the standard mathematical operators (+, -, *, /, etc.) and comparison operators (>, <, ==, etc.) in our classes as custom data types, just as we would use for built-in data types like int, float, and str.

Why use Operator Overloading in Python?

It allows us to create more readable and intuitive code.

Example -

For instance, consider a custom class that represents a point in 2D space. You could define a method called 'add' to add two points together, but using the '+' operator to add the 2 points makes the code more concise and readable

p1 = Point(1, 2)
p2 = Point(3, 4)
p3 = p1 + p2
print(p3.x, p3.y) # prints 4, 6

How to overload an operator?

To overload an operator we can use specialized methods in our class. These methods are identified by their names, which start and end with double underscores (__). Here are some of the most commonly used overloaded operators and their corresponding special methods:

+ : __add__
- : __sub__
* : __mul__
/ : __truediv__
< : __lt__
> : __gt__
== : __eq__

For example - if we want to overload the + operator to add two instances of a custom class, you would define the add method.

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other): #operator overloading
        return Point(self.x + other.x, self.y + other.y)

Note - Operator overloading is not just limited to built-in operators but we can also overload any user-defined operator

More Example -

In the below example, we defined a vector class and we overloaded the add operator to add two instances of vector class

class Vector:
  def __init__(self, i, j, k):
    self.i = i
    self.j = j
    self.k = k

  def __str__(self):
    return f"{self.i}i + {self.j}j + {self.k}k"

  def __add__(self, x):
    return Vector(self.i + x.i,  self.j+x.j, self.k+x.k) 
v1 = Vector(3, 5, 6)
print(v1)

v2 = Vector(1, 2, 9)
print(v2)

print(v1 + v2)
print(type(v1 + v2))
3i + 5j + 6k
1i + 2j + 9k
4i + 7j + 15k
<class '__main__.Vector'>

Resources Used

You can watch the video of Day#77 by clicking on the below link πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡

Conclusion

Thanks, guys for going through this blog post. On day 77, I learned about a powerful Python class feature that allows redefining the behavior of mathematical and comparison operators for custom data types, you can write code that is both concise and expressive. However, a word of caution to keep in mind is that overloading the wrong operator or using it inappropriately can lead to confusing or unexpected behavior.

Thank you if you read this post and have found this post useful. I hope you have joined me and are enjoying my magical journey of Python coding. This is it for Day #77

See you in the next one.....


About Me

Hey Guys, I am Chintan Jain from CodeWithJain. I am a trader and content creator. I am also passionate about tech and hence wanted to explore the field of tech. I always wanted to learn to code so I watched many tutorials but procrastinated practicing coding. To get into the habit of coding consistently I am starting to BLOG with HASHNODE on daily basis.

I will document my coding journey from scratch and share my daily learnings in a blog post on HASHNODE. I hope you all will enjoy my content and my coding journey.

So what are you waiting for, smash the FOLLOW and LIKE buttons and follow along my coding journey, a step to create more beautiful digital products and empower people.


Β