Way back when I was learning to code, the concept of overloading operators was confusing to me. I think this was partly due to the R language not having the typical definition of classes, which made it a little less straightforward to understand why operator overloading might be useful.

The need for operator overloading arises when you try to answer the following question:

“When you combine two variables with the + operator how does Python know when to add them if they’re integers or concatenate them if they’re strings?”

Basically you need to tell Python what to do with the + operator so that it knows what to do given variables of a different type.

We can accomplish this by defining a class, which allows us to bundle together objects (i.e. data attributes) and functions that allow us to interact with these objects (i.e. methods). The class below defines creates a data attribute that contains the list of numbers that the user provides when it is instantiated.

class vec0:
    def __init__(self, data):
        self.data = data

x = vec0([1,4,1,2,6])

Suppose we want to implement element-wise addition: add an a value to each element in the list. If we try to do something like x + 3 we’ll get a TypeError. We could use list comprehension but that would look a little clunky.

x_sum = [item + 3 for item in x.data]

A more concise way to implement this is to overload the + operator. We can do this by defining the add method in the above class. Below we inherit the methods from the class defined above and overload the addition operator to implement element-wise addition.

class vec1(vec0):
    def __add__(self, y):
        result = [item + y for item in self.data]

x = vec1([1,4,1,2,6])
print(x + 3)

That’s all there is to it. You can overload all sorts of operators. A list of operators is provided in the Python documentation.