Stack operator in Python

You can change the meaning of the operator in Python depending on the operand used and we call that operator overloading.

What is operator overloading in Python?

Python operators work with built-in functions, but an operator can be used to perform many different operations. For example with the '+' operator, you can add arithmetic to two numbers together, can combine two lists, or join two different strings .

This feature in Python is called operator overloading, allowing the same operator to be used differently depending on the context.

Stack operator in Python Picture 1

So what happens when we use operator overloading with the object of a class declared by the user? Follow the example of simulating a point in the following two-dimensional coordinate system:

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

We run the program and enter the points:

 >>> p1 = Point(2,3) 
>>> p2 = Point(-1,2)
>>> p1 + p2
Traceback (most recent call last):
.
TypeError: unsupported operand type(s) for +: 'Point' and 'Point'

The program immediately reports a TypeError error because Python cannot receive two Point objects at the same time.

To handle this problem, we will use operator overloading.

First, learn some of the following special functions.

Special functions in Python

The function in Class begins with two consecutive underscores (__) which are special functions, which have special meanings.

There are many special functions in Python, one of which is the __init __ () function that Quantrimang introduced earlier in the Class and Object lesson. This function is called whenever an object is initialized, a new variable in the class.

The purpose of using these special functions is to make our functions compatible with Python built-in functions.

 >>> p1 = Point(2,3) 
>>> print(p1)

You should declare the __str __ () method in the class to control how the results are printed.

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

def __str__(self):
return "({0},{1})".format(self.x,self.y)

And now try again with the print () function .

 >>> p1 = Point(2,3) 
>>> print(p1)
(2,3)

Using __str __ () results in a more standard display. Also you can print the same result using Python's built-in function str () or format ().

 >>> str(p1) 
'(2,3)'

>>> format(p1)
'(2,3)'

When using str () and format (), Python executes the call p1 .__ str __ (), so the result is returned similarly.

Overload '+' operator in Python

To overload the '+' operator, we will use the __add __ () function in the class. We can deploy many jobs using this function, such as adding two coordinates in the example above.

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

def __str__(self):
return "({0},{1})".format(self.x,self.y)

def __add__(self,other):
x = self.x + other.x
y = self.y + other.y
return Point(x,y)

We run the program and enter the points:

 >>> p1 = Point(2,3) 
>>> p2 = Point(-1,2)
>>> print(p1 + p2)
(1,5)

In this program, when you execute p1 + p2 , Python will call p1 .__ add __ (p2).

Similarly, you can overload many other operators. Quantrimang would like to introduce some special functions for operator overloading in the table below:

MATHEMATICS OF ACTIVITIES P1 + p2 p1 .__ add __ (p2) Subtraction p1 - p2 p1 .__ sub __ (p2) Multiplication p1 * p2 p1 .__ mul __ (p2) Excess p1 ** p2 p1 .__ pow __ (p2 ) Division p1 / p2 p1 .__ truediv __ (p2) Partial division division p1 // p2 p1 .__ floordiv __ (p2) Balance (modulo) p1% p2 p1 .__ mod __ (p2) Operation on bit: left translation p1 << p2 p1 .__ lshift __ (p2) Bit manipulation: right shift p1 >> p2 p1 .__ rshift __ (p2) Bit manipulation: permission AND p1 & p2 p1 .__ and __ (p2) Operation on bit: enable OR p1 | p2 p1 .__ or __ (p2) Bit operation: XOR p1 ^ p2 p1 .__ xor __ (p2) Bit operation: NOT ~ p1 p1 .__ invert __ ()

Overload comparison operator in Python

Python is not only limited to overloading math operators, but also allowing users to overload comparison operators.

There are many comparison operators supported by Python, such as: <,>, <=,> =, ==, .

You use this operator overload when you want to compare objects in the class together.

For example, if you want to compare points in a class point , compare the magnitude of these points starting from the origin, doing the following:

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

def __str__(self):
return "({0},{1})".format(self.x,self.y)

def __lt__(self,other):
self_mag = (self.x ** 2) + (self.y ** 2)
other_mag = (other.x ** 2) + (other.y ** 2)
return self_mag < other_mag

We run the program and enter the points and operators used to compare:

 >>> Point(1,1) < Point(-2,-3) 
True

>>> Point(1,1) < Point(0.5,-0.2)
False

>>> Point(1,1) < Point(1,1)
False

Similarly, you can overload many other comparison operators. Quantrimang would like to introduce some special functions for comparison operator overloading in the table below:

OPERATING ACTIVITIES Smaller than p1 p1 .__ eq __ (p2) Other p1! = p2 p1 .__ ne __ (p2) Larger than p1> p2 p1 .__ gt __ (p2) Greater than or equal to p1> = p2 p1 .__ ge __ (p2)

See more:

  1. Operator overloading in C #
  2. Overload relational operator in C ++
  3. Object-oriented programming in Python

Previous article: Multiple Inheritance in Python

4 ★ | 1 Vote

May be interested

  • More than 100 Python exercises have solutions (sample code)More than 100 Python exercises have solutions (sample code)
    more than 100 python code examples are shared by guy zhiwehu on github, however, the solution of this series is written on the old python version. following tipsmake.com will be vietnameseized and edited to suit python 3.x to help you learn and practice python.
  • Bookmark 5 best Python programming learning websitesBookmark 5 best Python programming learning websites
    if you are a developer or you are studying and want to stick with this industry, learn python to add a highlight in your journey.
  • For in Python loopFor in Python loop
    in this article, we will learn more about for for loop in python as well as its variations, how to use for to repeat a string of elements in python such as list, string or other iterative objects.
  • Manage files and folders in PythonManage files and folders in Python
    python also provides a variety of methods to handle various directory-related operations. in this article, we will learn about managing files and directories in python, namely creating folders, renaming folders, listing folders and working with them.
  • How to Become a Full Stack ProgrammerHow to Become a Full Stack Programmer
    a full-stack programmer is a versatile developer who has experience and understanding of front-end and back-end software and hardware. full-stack developers also have a firm grasp of a multitude of programming languages, making them agile...
  • Multiple choice quiz about Python - Part 3Multiple choice quiz about Python - Part 3
    today's topic quantrimang wants to challenge you is about file and exception handling in python. let's try the following 15 questions!
  • 5 choose the best Python IDE for you5 choose the best Python IDE for you
    in order to learn well python, it is essential that you find yourself an appropriate ide to develop. quantrimang would like to introduce some of the best environments to help improve your productivity.
  • What is Python? Why choose Python?What is Python?  Why choose Python?
    python is a powerful, high-level, object-oriented programming language, created by guido van rossum. python is easy to learn and emerging as one of the best introductory programming languages ​​for people who are first exposed to programming languages.
  • Module time in PythonModule time in Python
    python has a time module used to handle time-related tasks. tipsmake.com will work with you to find out the details and functions related to the time specified in this module. let's follow it!
  • Python data type: string, number, list, tuple, set and dictionaryPython data type: string, number, list, tuple, set and dictionary
    in this section, you'll learn how to use python as a computer, grasp python's data types and take the first step towards python programming.