Python operator overloading


Python supports operator overloading. In Python operators work with many classes. Like the + operator works on numbers, lists and strings but they are of different types. So depending on the class, they mean different things.

Related course: Complete Python Programming Course & Exercises

Introduction

In Python operators like +,- can be used on different types of data. So for example all of these works:

>>> x = 1 + 2
>>> y = "a" + "b"
>>> z = [1,2,3] + [4,5,6]

But they are based on different classes

>>> type(x)
<class 'int'>
>>> type(y)
<class 'str'>
>>> type(z)
<class 'list'>

We'll discuss these points in the article:

  1. Why learning operator overload
  2. Introduction
  3. Caveat

python operator overloading

Why the operator override is needed?

Please see the following examples.

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

p1=Point(1,1)
p2=Point(2,2)
print(p1+p2)

But the compiler shows you this message.

`TypeError: unsupported operand type(s) for +: 'Point' and 'Point'`

That is, python does not support direct addition of two points, so this is the time to get a brief knowledge of operator overloading.

How to overload an operator in python?

Python operators apply to built-in classes, however, the same programmer will behave differently on different types. This feature in Python allows the same operation to have different meanings depending on the context and is called operator overloading.

Example.

Input

class Point:
    def __init__(self,x=0,y=0):
        self.x=x
        self.y=y
    def __str__(self):
        return "({},{})".format(self.x,self.y)
    def __add__(self, other):
        x = self.x+other.x
        y = self.y+other.y
        return Point(x,y)
p1=Point(1,1)
p2=Point(2,2)
p3=Point(3,3)
print(p1+p2+p3)
print(type(p1+p2+p3))

Output

`(6,6) <class '__main__.Point'>`

Special Functions in Python

This is an overview of special functions in Python, for operator overloading.

Magic Methods for Binary Operators in Python

OPERATOR MAGIC METHOD
+ add(self, other)
sub(self, other)
* mul(self, other)
/ truediv(self, other)
// floordiv(self, other)
% mod(self, other)
** pow(self, other)

Magic Methods for Comparison Operators in Python

OPERATOR MAGIC METHOD
< lt(self, other)
> gt(self, other)
<= le(self, other)
>= ge(self, other)
== eq(self, other)
!= ne(self, other)

Magic Methods for Assignment Operators in Python

OPERATOR MAGIC METHOD
-= isub(self, other)
+= iadd(self, other)
*= imul(self, other)
/= idiv(self, other)
//= ifloordiv(self, other)
%= imod(self, other)
**= ipow(self, other)

Magic Methods for Unary Operators

OPERATOR MAGIC METHOD
neg(self, other)
+ pos(self, other)
~ invert(self, other)

Notes.

Note 1: Do not write the return statement as return "({},{})".format(x,y) or return "({0},{1})".format(x,y) when implementing the add method

Reason: The type of return value written in the above form is string. if the operands are limited to two, no errors will occur; however, when three points are added simultaneously, the compiler will report an error. As follows.

`TypeError: can only concatenate str (not "Point") to str`

Therefore, a return value of type Point(x,y) is required.

Note 2: Note the order of execution of the program, take print(p1+p2) as an example, at print(p1+p2) the breakpoint, debug the program found the order of add->init->add->print->str->print

Reason: After the init method is called, x,y will be returned as an object to Point(x,y) in the add statement and then to the following print statement, because the return type is Point class, so the str method will be unconditionally executed to format the output, and the result will be converted to a string and then output the result with print(p1+p2).

The specific execution process can be carefully viewed by the debugging function.