Python is a very dynamic programming language. In Python, we can change the meaning of an operator depending upon the context it is being used. In this post, we will explore how to use operator overloading in Python.
Python operators work for built-in classes. But the same operator behaves differently with different types. For example, the + operator will perform arithmetic addition on two numbers, merge two lists, or concatenate two strings.
This feature in Python that allows the same operator to have different meaning according to the context is called operator overloading.
Let's take a look at a simple example.
As we can see in the examples above, the same addition (+) operator works differently and appropriately depending on the data provides to it.
So, how do these built-in operators like, +, -, *, /, etc work for user-defined classes? Or, will it even work at all?
Let's create a simple class and try.
As we see above, Python throws an error that our class 'Point' does not support the + operator.
So, how can we make our custom class to support it like built-in classes?
We can do that by implement or overload a predefined special function in Python called __add__
As we see above, now it does not throw any error any more, but it create a new Point object as a result of adding two points.
There are many other pre-defined special functions like __add__ in Python, each of them has a purpose and we can overload any of them to create specific meaning for our class.
Some of most common special functions are below.
One of another most common special function that we often overload is the __str__ function.
In our example above, when we print out a Point object, it prints the memory address of that object. How about we want to print out something more meaningful and user-friendly?
That's what the special __str__ function is for, how to convert an object to a string.
Now, it all works and looks good as we expect. That's how we overload operators in Python.
Happy Overloading!
Source code: https://github.com/MaiaNgo/python-advanced/blob/main/polymorphism/operator_overloading.ipynb