Member-only story
Python Operator Overloading
Give another meaning to a common operator in a different context
Operator overloading in Python means giving another meaning to a common operator in a different context.
For example, you can sum up two integers with the addition operator +
:
1 + 2
But you cannot sum up instances of a custom class by default:
apple + banana
But you can change this. To use the addition operator +
for custom objects, you need to overload the operator +
.
Today you learn how to overload operators to make Python operations possible on your objects.
Special Methods in Python
Before jumping into operator overloading in Python, it’s important you understand the concept of special methods (also called double underscore methods or dunder methods).
The simplest example of a special method is the __init__
method of a class. This method is called when a new instance of a class is created.
For example:
The last line in the above code runs the __init__
method of the Bill
class. In this case, it assigns a value to the instance.
Let’s try to print the instance:
print(ten_dollars)
Output:
<__main__.Bill object at 0x7fd2bcf99d00>
This unambiguous output makes no sense. If you’d like to print the amount of money by default instead, you can provide an implementation to a special method called __str__
. It defines the string representation of the object. This method is called under the hood whenever you call print
on an object.
For example: