• Python - Home
  • Python - Introduction
  • Python - Syntax
  • Python - Comments
  • Python - Variables
  • Python - Data Types
  • Python - Numbers
  • Python - Type Casting
  • Python - Operators
  • Python - Booleans
  • Python - Strings
  • Python - Lists
  • Python - Tuples
  • Python - Sets
  • Python - Dictionary
  • Python - If Else
  • Python - While Loop
  • Python - For Loop
  • Python - Continue Statement
  • Python - Break Statement
  • Python - Functions
  • Python - Lambda Function
  • Python - Scope of Variables
  • Python - Modules
  • Python - Date & Time
  • Python - Iterators
  • Python - JSON
  • Python - File Handling
  • Python - Try Except
  • Python - Arrays
  • Python - Classes/Objects
  • Python - Inheritance
  • Python - Decorators
  • Python - RegEx
  • Python - Operator Overloading
  • Python - Built-in Functions
  • Python - Keywords
  • Python - String Methods
  • Python - File Handling Methods
  • Python - List Methods
  • Python - Tuple Methods
  • Python - Set Methods
  • Python - Dictionary Methods
  • Python - Math Module
  • Python - cMath Module
  • Python - Data Structures
  • Python - Examples
  • Python - Q&A
  • Python - Interview Questions
  • Python - NumPy
  • Python - Pandas
  • Python - Matplotlib
  • Python - SciPy
  • Python - Seaborn

AlphaCodingSkills

  • Programming Languages
  • Web Technologies
  • Database Technologies
  • Microsoft Technologies
  • Python Libraries
  • Data Structures
  • Interview Questions
  • PHP & MySQL
  • C++ Standard Library
  • C Standard Library
  • Java Utility Library
  • Java Default Package
  • PHP Function Reference

Python - Assignment Operator Overloading

Assignment operator is a binary operator which means it requires two operand to produce a new value. Following is the list of assignment operators and corresponding magic methods that can be overloaded in Python.

Example: overloading assignment operator

In the example below, assignment operator (+=) is overloaded. When it is applied with a vector object, it increases x and y components of the vector by specified number. for example - (10, 15) += 5 will produce (10+5, 15+5) = (15, 20).

The output of the above code will be:

AlphaCodingSkills Android App

  • Data Structures Tutorial
  • Algorithms Tutorial
  • JavaScript Tutorial
  • Python Tutorial
  • MySQLi Tutorial
  • Java Tutorial
  • Scala Tutorial
  • C++ Tutorial
  • C# Tutorial
  • PHP Tutorial
  • MySQL Tutorial
  • SQL Tutorial
  • PHP Function reference
  • C++ - Standard Library
  • Java.lang Package
  • Ruby Tutorial
  • Rust Tutorial
  • Swift Tutorial
  • Perl Tutorial
  • HTML Tutorial
  • CSS Tutorial
  • AJAX Tutorial
  • XML Tutorial
  • Online Compilers
  • QuickTables
  • NumPy Tutorial
  • Pandas Tutorial
  • Matplotlib Tutorial
  • SciPy Tutorial
  • Seaborn Tutorial

Learn Python practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn python interactively, python introduction.

  • Get Started With Python
  • Your First Python Program
  • Python Comments

Python Fundamentals

  • Python Variables and Literals
  • Python Type Conversion
  • Python Basic Input and Output

Python Operators

Python Flow Control

  • Python if...else Statement
  • Python for Loop
  • Python while Loop
  • Python break and continue
  • Python pass Statement

Python Data types

  • Python Numbers and Mathematics
  • Python List
  • Python Tuple
  • Python String
  • Python Sets
  • Python Dictionary
  • Python Functions
  • Python Function Arguments
  • Python Variable Scope
  • Python Global Keyword
  • Python Recursion
  • Python Modules
  • Python Package
  • Python Main function

Python Files

  • Python Directory and Files Management
  • Python CSV: Read and Write CSV files
  • Reading CSV files in Python
  • Writing CSV files in Python
  • Python Exception Handling
  • Python Exceptions
  • Python Custom Exceptions

Python Object & Class

  • Python Objects and Classes
  • Python Inheritance
  • Python Multiple Inheritance
  • Polymorphism in Python

Python Operator Overloading

Python advanced topics.

  • List comprehension
  • Python Lambda/Anonymous Function
  • Python Iterators
  • Python Generators
  • Python Namespace and Scope
  • Python Closures
  • Python Decorators
  • Python @property decorator
  • Python RegEx

Python Date and Time

  • Python datetime
  • Python strftime()
  • Python strptime()
  • How to get current date and time in Python?
  • Python Get Current Time
  • Python timestamp to datetime and vice-versa
  • Python time Module
  • Python sleep()

Additional Topic

Precedence and Associativity of Operators in Python

  • Python Keywords and Identifiers
  • Python Asserts
  • Python Json
  • Python *args and **kwargs

Python Tutorials

Python dir()

  • Python object()

Python Lists Vs Tuples

In Python, we can change the way operators work for user-defined 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 .

  • Python Special Functions

Class functions that begin with double underscore __ are called special functions in Python.

The special functions are defined by the Python interpreter and used to implement certain features or behaviors.

They are called "double underscore" functions because they have a double underscore prefix and suffix, such as __init__() or __add__() .

Here are some of the special functions available in Python,

Example: + Operator Overloading in Python

To overload the + operator, we will need to implement __add__() function in the class.

With great power comes great responsibility. We can do whatever we like inside this function. But it is more sensible to return the Point object of the coordinate sum.

Let's see an example,

In the above example, what actually happens is that, when we use p1 + p2 , Python calls p1.__add__(p2) which in turn is Point.__add__(p1,p2) . After this, the addition operation is carried out the way we specified.

Similarly, we can overload other operators as well. The special function that we need to implement is tabulated below.

  • Overloading Comparison Operators

Python does not limit operator overloading to arithmetic operators only. We can overload comparison operators as well.

Here's an example of how we can overload the < operator to compare two objects the Person class based on their age :

Here, __lt__() overloads the < operator to compare the age attribute of two objects.

The __lt__() method returns,

  • True - if the first object's age is less than the second object's age
  • False - if the first object's age is greater than the second object's age

Similarly, the special functions that we need to implement, to overload other comparison operators are tabulated below.

  • Advantages of Operator Overloading

Here are some advantages of operator overloading,

  • Improves code readability by allowing the use of familiar operators.
  • Ensures that objects of a class behave consistently with built-in types and other user-defined types.
  • Makes it simpler to write code, especially for complex data types.
  • Allows for code reuse by implementing one operator method and using it for other operators.
  • Python Classes and Objects
  • self in Python, Demystified

Table of Contents

  • Introduction
  • Example: + Operator Overloading

Sorry about that.

Related Tutorials

Python Tutorial

Python Library

BlogsDope image

Operator Overloading in Python

submit your article

Operator overloading refers to the ability of a built-in operator to behave differently according to the different operands we use with it.

For example, the operator ‘+’ is used to: 

  •  Add two integers. 
  • Concatenate two strings.
  • Merge two lists.

WelcomeWelcomeWelcome 

Advantages of Operator Overloading:

  • It provides reusability, instead of writing multiple methods that differ slightly we can simply write one method and overload it.
  •  It also improves code clarity and eliminates complexity.
  •  It makes code concise and simple to understand. 

Why operator overloading? 

Consider two objects of a user-defined data type, now if we try to multiply both with an operator * the compiler will throw an error because the compiler doesn’t know how to multiply the operands.

For example, let's take a case where we have defined our own  Coordinates class with two attributes  x  and  y . Now, objects of this class would represent different points and using ​ +  directly on these points (objects) would give us an error. Let's look at the example to understand this.

​ Traceback (most recent call last): File "<string>", line 9, in <module> 

 print(p1+p2) 

​ TypeError: unsupported operand type(s) for +: 'Coordinates' and 'Coordinates'. 

Here, the compiler is unable to understand what p1+p2 means.

To resolve this problem we can define a method to overload the + operator to change its functionality as per our needs.

​How to perform operator overloading?

Here we have defined the __add()__ method and passed the Coordinates object and got the sum of the coordinates as the result.

This is how we can define the magic methods and can also change their behavior according to our needs .

In python whenever we use ‘+’ operator, python directly call the method that is associated to it i.e. __add()__ method.​

Python arithmetic on two complex numbers :

​Enter real and imaginary part of complex No - 1(separeated by space)

Enter real and imaginary part of complex No - 2(separeated by space) 

Addition: 6.00+8.00i 

Subtraction: -2.00-2.00i

Here, we have entered two complex numbers, containing their real and imaginary parts. 

Now, these numbers are passed to the complex function, defined by us. 

After writing (A+B) python will automatically call the __add__() function because of ( + ) symbol. The same will happen for ( - ) symbol, the __sub__() function will be called.

Our function will now add and subtract, both real and imaginary parts of the numbers together, simultaneously. 

Now, the results will be passed to the __str()__ function, which will concatenate both the real and imaginary parts together.

Python magic function for binary operators overloading  

Python magic function for comparison operators overloading 

Python doesn't limit operator overloading to arithmetic operators. We can overload other operators like comparison, assignment operators as well.

For Example: If we want to overload greater than ( > ) and equal to operator ( == )

m1 is greater than m2 

Here we are passing two numbers into the function.

Case 1- After writing m1>m2 , python will automatically call the __gt__() function, because of the ( > ) symbol

Case 2- Similarly, __eq__() will be called automatically after writing m3==m4 . 

Once the conditions are checked, we will get our result.

Table of the magic methods for comparison operators:

Python magic function for assignment operators overloading

Assignment operators perform a particular operation on the value of a variable and assign the result to that variable.  

Now move ahead to the next chapter.

Learn the Python Programming Language and strengthen your grip on the subject. 

C++ : Linked lists in C++ (Singly linked list)

Adding outline to text using css, set, toggle and clear a bit in c, 12 creative css and javascript text typing animations, inserting a new node to a linked list in c++, pow() in python, dutch national flag problem - sort 0, 1, 2 in an array, memoryview() in python, next() in python, map() in python, mouse rollover zoom effect on images, important functions in math.h library of c, formatting the print using printf in c, linked list traversal using loop and recursion in c++, calculator using java swing and awt with source code, animate your website elements with css transforms, controlling the outline position with outline-offset, prime numbers using sieve algorithm in c.

article on blogsdope

Please login to view or add comment(s).

overload assignment operator python

Operator Overloading in Python

Operator Overloading is the phenomenon of giving alternate/different meaning to an action performed by an operator beyond their predefined operational function. Operator overloading is also called  Operator Ad-hoc Polymorphism .

Python operators work for built-in classes. But the same operator expresses differently with different types. For example, The + operator will perform arithmetic addition on two numbers, merge two lists and concatenate two strings. Python allows the same operator to have different meanings according to the referring context.

Example: Depicting different use of basic arithmetic operators

How to overload an operator in python.

To perform operator overloading, Python provides some special function or magic function that is automatically invoked when it is associated with that particular operator. For example, when we use + operator, the magic method __add__ is automatically invoked in which the operation for + operator is defined.

Special Functions in Python

Global functions that begin with double underscore __ are called special functions in Python. It’s because they are not ordinary. The __init__() function which we usually define and resemble as a constructor is one of them. It gets called every time we create a new object of that class.

Magic Methods for Binary Operators in Python

Magic methods for comparison operators in python, magic methods for assignment operators in python, magic methods for unary operators, example: overloading binary + operator in python.

When we use + operator, the magic method __add__ is automatically invoked in which the operation for + operator is defined. Hence by changing the magic method’s code, we can give alternative meaning to the + operator.

Example: Overloading comparison operators in Python

Example: sample operator overloading program.

  • Python Operator Overloading
  • Python Comparison Operators

What is Operator Overloading in Python (with Examples)

  • by Rajkumar Bhattacharya
  • April 1, 2022 April 1, 2022

Operator overloading in Python

Page Contents

In this tutorial we will learn about Operator Overloading in Python . Before reading this tutorial we recommended to read about below tutorials –

  • Object Oriented Programming in Python – An Intro for Beginners
  • Inheritance in Python – A Detailed Explanation with Examples

Operator Overloading in Python

Operator Overloading refers to different uses of the same operator in different situations. For example, if we use + operator in between two integer number , it returns their sum, if we use + in between two string , it concatenates them and if we use + in between two lists, it adds the two lists . This various use of the same + operator is called Operator Overloading .

Now the question that may arise in our minds is what will happen if we use the + operator between two objects, we will see it with the help of an example –

Example 1: Try to add two objects using + operator in Python

In the above code, a class named Employee has been defined which have two object variables named name and salary . Then two objects of that class named emp1 and emp2 have been created. Then an attempt was made to add two objects using the + operator which raised TypeError .

So we can’t add two objects with the + operator. But Python gives us some methods by which we can add two objects through the + operator, these methods are called Special method or Magic method or Dunder method .

Special method in Python

Inside any Python class those methods which start with double underscore ( __ ) and end with double underscore ( __ ) are called Special method . These methods are different from other methods in the class. Earlier we discussed one such method that is Constructor or __init__() method. Now we will discuss about various types of Special Method in Python –

__str__() and __repr__() method in Python

When we try to print an object of a class, it prints an object which does not make sense at all. With the __str__() and __repr__() method we can control what will print in the output if we print any object. Some of the features of __str__() and __repr__() method are as under –

  • If __str__() or __repr__() method is defined in a class then if we try to print any object of the class then __str__() or __repr__() method is automatically called.
  • If both __str__() and __repr__() methods are defined in a class then the __str__() method is automatically called if we try to print any object in the class. We can also explicitly call __str__() and __repr__() when printing objects.

Example 1: Print an object in Python

In the above code, an object emp1 of Employee class has been printed. Since there is no __str__() or __repr__() method defined in the class, so seeing the output we can not understand anything about the object .

Example 2: Print an object with __repr__() method in Python

In the above code, when an object emp1 of Employee class is printed, it automatically calls __repr__() method.

Example 3: Print an object with __str__() method in Python

In the above code, when an object emp1 of Employee class is printed, it automatically calls __str__() method.

Example 4: Print an object with both __str__() and __repr__() method

In the above code, when an object emp1 of Employee class is printed, it automatically calls the __str__() method as both __str__() and __repr__() method is defined in the class . But when we have printed the object explicitly calling with __str__() and __repr__() method it has called __str__() and __repr__() method respectively .

Overloading Arithmetic Operators in Python

When we use any arithmetic operator with any object then which special method will be called is shown in a table below –

Example 1: Arithmetic Operators Overloading in Python

+ arithmetic operator overloading in python, – arithmetic operator overloading in python, * arithmetic operator overloading in python, / arithmetic operator overloading in python, // arithmetic operator overloading in python, % arithmetic operator overloading in python, ** arithmetic operator overloading in python, & arithmetic operator overloading in python, ^ arithmetic operator overloading in python, | arithmetic operator overloading in python, example 2: add multiple objects in python using + operator.

If we need to add more than two objects with __add__() method then we can’t do it in the manner mentioned above, we will see adding more than two objects with __add__() method below. For this reason we will use __str__() and __repr__() method .

When emp1 + emp2 + emp3 + emp4 is written in the above code, first a new object Employee(“emp1”, 8) is created using emp1 + emp2 and __add__() method . Then this new object is added to emp3 and Created another new object Employee (“emp1”, 12) , with which emp4 is added to create another new object Employee (“emp1”, 28) which is assigned to emp . So when we print the emp the __repr__() method is automatically called and printed 28 .

In this way other special methods can be used for more than two objects.

Overloading Comparison Operators in Python

In Python we can overload comparison operator like arithmetic operator. When we use any comparison operator with any object then which special method will be called is shown in a table below

Example 1: Comparison Operators Overloading in Python

< comparison operator overloading in python, <= comparison operator overloading in python, == comparison operator overloading in python, = comparison operator overloading in python, > comparison operator overloading in python, >= comparison operator overloading in python, overloading assignment operators in python.

In Python we can overload assignment operators like arithmetic operators. When we use any assignment operator with any object then which special method will be called is shown in a table below

Example 1: Assignment Operators Overloading in Python

+= assignment operator overloading in python, -= assignment operator overloading in python, *= assignment operator overloading in python, /= assignment operator overloading in python, //= assignment operator overloading in python, %= assignment operator overloading in python, **= assignment operator overloading in python, &= assignment operator overloading in python, ^= assignment operator overloading in python, |= assignment operator overloading in python.

Thank you for reading this Article . If You enjoy it Please Share the article . If you want to say something Please Comment  .

Share this:

overload assignment operator python

Recommended Articles

Leave a reply cancel reply.

Basics of Python

  • Getting started with Python
  • Introduction to IDLE
  • Python 2.x vs. Python 3.x
  • Syntax Rules and First Program
  • Numbers and Math Functions
  • Modules and Functions
  • Input and Output
  • String in Python
  • String Functions

Complex Datatypes

  • Lists in Python
  • Utilizing List Elements by Iterating
  • Deleting List Elements & other Functions
  • Dictionaries in Python
  • Functions for Dictionary
  • Tuples in Python
  • Relational and Logical Operators
  • Conditional Statements

OOPS Concept

  • Define Functions in Python
  • Introduction to OOP
  • Object Oriented Programming in Python
  • Classes in Python
  • The concept of Constructor
  • Destructors - Destroying the Object
  • Inheritance in Python
  • Access Modifers in Python
  • Types of Inheritance
  • Method Overriding
  • Polymorphism
  • static Keyword
  • Operator Overloading

Error Handling

  • Introduction to Error Handling
  • Exception Handling: try and except
  • Exeption Handling: finally
  • Exception Handling: raise
  • File Handling
  • Reading and Writing File

Multithreading

  • Introduction to Multithreading
  • Threading Module in Python
  • Thread Object
  • Lock Object
  • RLock Object
  • Event Object
  • Timer Object
  • Condition Object
  • Barrier Object

Miscellaneous

  • __name__ Variable in Python
  • Iterable and Iterator
  • yield Keyword
  • Python Generators
  • Python Closures
  • Python Decorators
  • @property Decorator in Python
  • Assert Statement
  • Garbage Collection
  • Shallow and Deep Copy

Python Logging

  • Introduction to Logging
  • Configure Log LEVEL, Format etc
  • Python Logging in a file
  • Python Logging Variable Data
  • Python Logging Classes and Functions

Python With MySQL

  • Python MySQL Introduction
  • Create Database - Python MySQL
  • Create Table - Python MySQL
  • Insert Data in Table
  • Select Data from Table
  • Update data in Table
  • Delete data from Table
  • Drop Table from Database
  • WHERE clause - Python MySQL
  • Order By clause - Python MySQL
  • Limit clause - Python MySQL
  • Table Joins - Python MySQL

Operator overloading in Python

Operators are used in Python to perform specific operations on the given operands. The operation that any particular operator will perform on any predefined data type is already defined in Python.

Each operator can be used in a different way for different types of operands. For example, + operator is used for adding two integers to give an integer as a result but when we use it with float operands , then the result is a float value and when + is used with string operands then it concatenates the two operands provided.

This different behaviour of a single operator for different types of operands is called Operator Overloading . The use of + operator with different types of operands is shown below:

Can + Operator Add anything?

The answer is No, it cannot. Can you use the + operator to add two objects of a class. The + operator can add two integer values, two float values or can be used to concatenate two strings only because these behaviours have been defined in python.

So if you want to use the same operator to add two objects of some user defined class then you will have to defined that behaviour yourself and inform python about that.

If you are still not clear, let's create a class and try to use the + operator to add two objects of that class,

Traceback (most recent call last): File "/tmp/sessions/1dfbe78bb701d99d/main.py", line 7, in print("sum = ", c1+c2) TypeError: unsupported operand type(s) for +: 'Complex' and 'Complex'

So we can see that the + operator is not supported in a user-defined class. But we can do the same by overloading the + operator for our class Complex . But how can we do that?

Special Functions in Python

Special functions in python are the functions which are used to perform special tasks. These special functions have __ as prefix and suffix to their name as we see in __init__() method which is also a special function. Some special functions used for overloading the operators are shown below:

Mathematical Operator

Below we have the names of the special functions to overload the mathematical operators in python.

Assignment Operator

Below we have the names of the special functions to overload the assignment operators in python.

Relational Operator

Below we have the names of the special functions to overload the relational operators in python.

It's time to see a few code examples where we actually use the above specified special functions and overload some operators.

Overloading + operator

In the below code example we will overload the + operator for our class Complex ,

sum = 7 + 7i

In the program above, __add__() is used to overload the + operator i.e. when + operator is used with two Complex class objects then the function __add__() is called.

__str__() is another special function which is used to provide a format of the object that is suitable for printing.

Overloading < operator

Now let's overload the less than operator so that we can easily compare two Complex class object's values by using the less than operaton < .

As we know now, for doing so, we have to define the __lt__ special function in our class.

Based on your requirement of comparing the class object, you can define the logic for the special functions for overriding an operator. In the code above, we have given precedence to the real part of the complex number, if that is less then the whole complex number is less, if that is equal then we check for the imaginary part.

Overloading operators is easy in python using the special functions and is less confusion too.

  • ← Prev
  • Next →
  • C programming

Python Introduction +

  • Python Introduction
  • Python History
  • Keywords And Data Types
  • Python Operators

Python Flow Control +

  • If Else Statement
  • Break And Continue

Python Functions +

  • Function Arguments
  • Recursive Functions
  • Python Modules
  • Python Packages

Python Native Data Types +

  • Python Numbers
  • Python Lists
  • Python Tuples
  • Python Strings
  • Python Sets
  • Python Dictionary

Python OOP +

  • Python Object And Class
  • Inheritance
  • Multiple Inheritance
  • Operator Overloading

File Handling +

  • Directory Management
  • Exception Handling

Advanced Topics +

  • Python Iterators
  • Python Generators
  • Python Closures
  • Python Decorators
  • Python @Property

Python Operator Overloading And Magic Methods

In this article, you will learn about Python operator overloading in which depending on the operands we can change the meaning of the operator. You will also learn about the magic methods or special functions in Python.

Operator Overloading In Python

Basically, operator overloading means giving extended meaning beyond their predefined operational meaning.

For example, a + operator is used to add the numeric values as well as to concatenate the strings. That’s because + is overloaded for int class and str class. But we can give extra meaning to this + operator and use it with our own defined class. This method of giving extra meaning to the operators is called operator overloading.

How to overload the operators in Python?

There is an underlying mechanism related to operators in Python .

The thing is when we use operators, a special function or magic function is automatically invoked that is associated with that particular operator.

For example, when we use + operator, the magic method __add__ is automatically invoked in which the operation for + operator is defined. So by changing this magic method’s code, we can give extra meaning to the + operator.

Just like __add__ is automatically invoked while using + operator, there are many such special methods for each operator in Python.

Overloading + operator in Python

As you can see in above example, we have overloaded + operator to add two objects by defining __add__ magic method and when we run the program it will generate following output.

That didn’t go as we expected. So, what we can do is to modify another magic method __str__ to produce the result as we desire.

Here is how we do it.

Now this will generate following output.

Python Magic Methods Or Special Functions

As we already there are tons of Special functions or magic methods in Python associated with each operator. Here is the tabular list of Python magic methods.

List of Assignment operators and associated magic methods.

List of Comparison operators and associated magic methods.

List of Binary operators and associated magic methods.

List of Unary operators and associated magic methods.

Example: Overloading extended assignment operator (+=) in Python

Example: overloading comparison(>) operator in python.

Operator Overloading In Python

Everything you need to know about the different types of Operator Overloading in Python

Nadim Jendoubi

Nadim Jendoubi

Python is a versatile and powerful programming language that offers various features to make code more expressive and concise. One such feature is operator overloading, which allows developers to redefine the behavior of operators such as +, -, *, /, and more.

By implementing operator overloading, we can extend the capabilities of built-in operators to work with custom objects and classes. This article dives into the concept of operator overloading in Python, exploring its benefits and demonstrating how it can be effectively used.

Operator Overloading 101

What is it.

Operator overloading refers to the ability to redefine the behavior of an operator for custom objects, i.e. it enables the seamless interaction of user-defined objects with infix operators such as + and |, as well as unary operators like - and ~.

Although it is criticized in certain communities, it is a language feature that, when misused, can result in programmer confusion, bugs, and unforeseen performance issues. However, when used properly, it leads to easily understandable code and APIs. Python achieves a favorable balance between flexibility, usability, and safety by imposing certain restrictions:

  • The meaning of operators for built-in types cannot be altered.
  • Only existing operators can be overloaded, i.e. we cannot create new operators.
  • Some operators, such as is , and , or , and not , cannot be overloaded, although bitwise operators like &, |, and ~ can be overloaded.

Benefits of operator overloading

We can notice different pros such as:

  • Enhanced Readability: By overloading operators, we can make our code more readable and expressive. It enables us to use familiar syntax with custom objects, making our code resemble the operations performed on built-in types.
  • Customized Behaviors: Operator overloading allows us to define specific behaviors for operators based on the context of our classes. For example, we can define addition (+) to concatenate strings or merge data structures, or define multiplication (*) to repeat elements in a custom sequence.
  • Code Reusability: By implementing operator overloading, we can reuse existing operators for our custom classes, reducing the need to write separate methods for each operation. This promotes code reusability and saves development time.

Overloading Unary Operators

Unary operators in Python are operators that perform operations on a single operand. They allow us to manipulate the value of a single object or variable. Python provides several unary operators, including:

  • Unary Minus Operator (-), implemented by __neg__ : This operator represents arithmetic unary negation. For example, if the value of x is -2, then the expression -x evaluates to 2.
  • Unary Plus Operator (+), implemented by __pos__ : This operator represents arithmetic unary plus. In most cases, x is equal to +x. However, there are a few scenarios where this equality does not hold true. .
  • Bitwise Complement Operator (~), implemented by __invert__ : This operator performs bitwise negation or bitwise inverse on an integer. It is defined as ~x == -(x+1). For instance, if the value of x is 2, then ~x evaluates to -3.

These special methods associated with the unary operators enable customized behavior and functionality when working with objects or variables in Python.

Overloading Arithmetic Operators

To illustrate the addition and multiplication operator overloading, we will pick up an old example of the Vector Class.

Although the official Python documentation states that sequences should use the + operator for concatenation and * for repetition, in the case of the Vector class, we will redefine the behavior of + and * to represent mathematical vector operations.

Addition Operator and Mixed Type Addition

Starting with the + operator, we overload it as such:

In order to facilitate operations involving objects of different types, Python incorporates a specialized dispatching mechanism for the infix operator special methods. When encountering an expression such as a + b, the interpreter follows a series of steps:

  • If object a possesses the __add__ method, the interpreter invokes        a. __add__ (b) and returns the result, unless the method returns NotImplemented .
  • If object a lacks the __add__ method or its invocation returns NotImplemented , the interpreter checks whether object b has the __radd__ method (reverse add). If present, it calls b. __radd__ (a) and returns the result, unless the method returns NotImplemented .
  • If object b does not have the __radd__ method or its invocation returns NotImplemented , the interpreter raises a TypeError with a message indicating unsupported operand types.

Flowchart for computing a + b with __add__ and __radd__, image taken from Fluent Python book

This mechanism ensures that Python gracefully handles operations involving objects of diverse types, attempting various avenues for finding a suitable method implementation.

Multiplication Operator and Mixed Type Multiplication

To enable mixed type multiplication and support scalar multiplication, we will implement the __mul__ method for regular multiplication and the __rmul__ method for reverse multiplication.

To facilitate Vector by Vector multiplication, we will use a distinct infix operator, specifically the "@" symbol, to denote this operation.

The special methods __matmul__, __rmatmul__, and __imatmul__ are associated with the "@" operator, which is named after matrix multiplication. Although these methods are currently not used within the standard library, they are recognized by the Python interpreter starting from Python 3. They provide support for the "@" operator and enable custom matrix multiplication operations.

Overview of Arithmetic Operators

By implementing the addition (+), multiplication (*), and matrix multiplication (@) operations, we have explored the fundamental patterns for coding infix operators. The techniques we have discussed can be applied to all the operators listed below, allowing for consistent and customizable behavior across a wide range of operations.

Infix operator method names,  image taken from Fluent Python book

Overloading Comparison Operators

The Python interpreter handles the comparison operators (==, !=, >, <, >=, and <=) in a manner similar to what we have discussed earlier, but with two significant differences:

  • Use of the same set of methods in forward and reverse operator calls, for example a forward call to __gt__ (greater than) is followed by a reverse call to __lt__ (less than), but with the arguments reversed.
  • Handling of == and != when the reverse method is missing is different, Python resorts to comparing the object IDs instead of raising a TypeError. This behavior allows for comparison of objects that do not explicitly define the reverse method.

These differences in handling the comparison operators provide flexibility and fallback options in case the reverse method is not implemented. It ensures that the comparison operations can still be performed effectively by resorting to alternate comparison strategies, such as comparing object IDs.

Overloading Augmented Assignment Operators

To implement augmented assignment operators in Python, we need to define the special methods that correspond to the desired operators. For example:

  • Addition and Assignment (+=): __iadd__(self, other) This method is called when the += operator is used. It should modify the current object's state by adding the value of other and return the modified object.
  • Subtraction and Assignment (-=): __isub__(self, other) This method is called when the -= operator is used. It should modify the current object's state by subtracting the value of other and return the modified object.
  • Multiplication and Assignment (*=): __imul__(self, other) This method is called when the *= operator is used. It should modify the current object's state by multiplying it with the value of other and return the modified object.
  • Division and Assignment (/=): __idiv__(self, other) This method is called when the /= operator is used. It should modify the current object's state by dividing it by the value of other and return the modified object.
  • Modulo and Assignment (%=): __imod__(self, other) This method is called when the %= operator is used. It should modify the current object's state by applying the modulo operation with the value of other and return the modified object.
  • Bitwise AND and Assignment: __iand__(self, other)
  • Bitwise OR and Assignment: __ior__(self, other)
  • Bitwise XOR and Assignment: __ixor__(self, other)

These methods should be implemented in our class to define the behavior of augmented assignment operators when applied to instances of that class. They should modify the object's state accordingly and return the modified object.

Operator overloading is a powerful feature in Python that allows us to redefine the behavior of operators for custom classes. It provides enhanced readability, customized behaviors, and code reusability. By leveraging operator overloading effectively, we can create more expressive and intuitive code, improving the overall design and functionality of our Python programs.

Further Reading

  • The "Why operators are useful" article .
  • the “Data Model” chapter of the Python documentation .

Common Index Anomalies and Database Performance Tuning

Uncover prevalent query anomalies and discover practical approaches to fine-tune database performance

From B-trees to GIN: Navigating Django's Database Index Landscape

Dive into the world of Django database indexes, exploring the power of B-trees, GIN, GiST, and BRIN to optimize performance.

How to Supercharge Your Django App: A Guide to Unleashing Peak Performance Through Database Indexing

Summary of the second chapter of the book "The Temple of Django Database Performance" Part I.

Iterators VS Generator VS Classic Coroutines in Python

Diving into Python's Iteration Arsenal: Explore the Magic of Iterators, Generators, and Coroutines to Streamline Data Handling and Asynchronous Programming.

#FutureSTEMLeaders - Wiingy's $2400 scholarship for School and College Students

What do you want to learn?

Operator Overloading in Python

Written by Rahul Lath

Updated on: 07 Dec 2023

Python Tutorials

tutor Pic

What is Operator Overloading in Python?

Operator overloading is a feature of Python that lets you use the same operator for more than one task.It lets programmers change the way an operator works by letting them define their own implementation for a certain operator for a certain class or object.The term “magic methods” refers to functions or techniques that are used to overload the operator.

Python overloading Because it enables developers to create user-defined objects that can act like built-in types, operator overloading is a crucial Python feature. Developers can specify how an object of a certain class will interact with other objects or with built-in operators by overloading the operators. Python is now more usable and flexible as a result.

We will talk about operator overloading in Python, why it’s important, and how to do it in this blog post. We will also show you some code examples to help you better understand how to use operator overloading in Python. 

Looking to Learn Python? Book a Free Trial Lesson and match with top Python Tutors for concepts, projects and assignment help on Wiingy today!

How to Overload Operators in Python?

Magic Methods and Their Usage

In Python, operator overloading is implemented using special functions or methods called magic methods. These methods have double underscores (__) at the beginning and end of their names. For example, the addition operator (+) is overloaded using the add method, and the less than operator (<) is overloaded using the lt method.

Magic methods are called automatically by Python when a particular operator is used with a user-defined object. For example, if you add two objects of a class that has overloaded the addition operator, Python will call the add method to perform the addition operation.

Example Code Snippets

Here are some examples of how to overload operators in Python:

  • Overloading the Addition Operator- To overload the addition operator, you can define the add method in your class. The following example shows how to overload the addition operator for a class that represents a point in two-dimensional space.

In the above example, we have defined the add method that takes another point object as an argument and returns a new point object with the sum of the x and y coordinates.

  • Overloading the Less Than Operator – To overload the less than operator, you can define the lt method in your class. The following example shows how to overload the less than operator for a class that represents a rectangle.

In the above example, we have defined the lt method that compares the area of two rectangle objects and returns True if the area of the first rectangle is less than the area of the second rectangle.

Overloading Binary + Operator in Python

A. Explanation of Binary + Operator Overloading-

 The binary addition operator (+) is one of the most commonly overloaded operators in Python. It is used to add two operands and produce a new value. In Python, we can overload the binary + operator to define the addition operation for our own classes.

To overload the binary + operator, we need to define the add method in our class. This method takes two operands as input and returns the result of the addition operation. When we use the + operator with our class objects, Python automatically calls the add method to perform the addition operation.

B. Example Code Snippets

Here’s an example of how to overload the binary + operator in Python:

In the above example, we have defined a class Fraction that represents a fraction with a numerator and a denominator. We have overloaded the binary + operator using the add method. This method takes another fraction object as input, adds the two fractions, and returns a new fraction object.

We have also defined the str method to display the fraction object in a readable format.

Here’s how to use the Fraction class with the overloaded binary + operator:

In the above code, we have created two fraction objects f1 and f2, and added them using the + operator. The output is the result of the addition operation, which is a new fraction object with the value 5/4.

How Does Operator Overloading Actually Work?

Operator overloading works by using the magic methods in Python. When we use an operator with a user-defined object, Python automatically calls the corresponding magic method to perform the operation.

For example, when we use the + operator with two objects of a class that has overloaded the + operator, Python calls the add method of that class to perform the addition operation.

Similarly, when we use the < operator with two objects of a class that has overloaded the < operator, Python calls the lt method of that class to perform the less than operation.

Here’s an example of how operator overloading works in Python:

Overloading Comparison Operators in Python

Explanation of Comparison Operator Overloading

 In addition to the binary + operator, we can also overload other operators in Python, such as the comparison operators (<, >, <=, >=, ==, and !=). Comparison operator overloading allows us to define how objects of our class should be compared to each other.

To overload a comparison operator, we need to define the corresponding magic method in our class. For example, to overload the less than (<) operator, we need to define the lt method in our class. When we use a comparison operator with our class objects, Python automatically calls the corresponding magic method to perform the comparison operation.

Example Code Snippets- Here’s an example of how to overload the less than (<) operator in Python:

In the above example, we have defined a class Vector that represents a two-dimensional vector with x and y coordinates. We have overloaded the less than (<) operator using the lt method. This method takes another vector object as input, compares the magnitudes of the two vectors, and returns a boolean value based on the comparison result.

Here’s how to use the Vector class with the overloaded less than (<) operator:

In the above code, we have created three vector objects v1, v2, and v3, and compared them using the less than (<) operator. The output is the result of the comparison operation, which is a boolean value based on the magnitudes of the vectors.

Advantages of Operator Overloading in Python

Explanation of Benefits of Operator

Overloading Operator overloading provides several benefits in Python. It allows us to define our own operators and customize their behavior for our own classes. This can make our code more concise, readable, and intuitive.

For example, if we define a class that represents a complex number, we can overload the binary + operator to define the addition operation for complex numbers. This allows us to write code like this:

This code is much more concise and readable than the alternative, which would be something like:

Here’s an example of how operator overloading can make our code more concise:

In the above example, we have defined a class Complex that represents a complex number with a real and imaginary part. We have overloaded the binary + operator using the add method to define the addition operation for complex numbers. This method takes another complex number as input, adds the real and imaginary parts of the two numbers, and returns a new Complex object.

We have then created three Complex objects c1, c2, and c3, and added c1 and c2 using the overloaded binary + operator. The result is a new Complex object c3 with a real part of 4 and an imaginary part of 6.

Overall, operator overloading is a powerful feature of Python that allows us to define our own operators and customize their behavior for our own classes. By doing so, we can make our code more concise, readable, and intuitive.

Overloading Built-in Functions

Python comes with a set of built-in functions that work with various types of objects. These functions are called “built-in” because they are included in the Python language itself and do not require any additional libraries or modules to use.

One of the advantages of using operator overloading is that it allows us to extend the functionality of these built-in functions to work with our own classes. This can make our code more concise, readable, and easier to work with.

  • Giving Length to Your Objects Using len()

The len() function is used to determine the length of an object, such as a string or a list. To make our own objects work with len(), we can define a method called len () in our class.

Here’s an example:

In the above example, we have defined a class called MyClass that stores a list of data. We have then defined the len () method to return the length of the data list. We can now use the len() function with objects of this class to determine their length.

  • Making Your Objects Work With abs()

The abs() function is used to determine the absolute value of a number. To make our own objects work with abs(), we can define a method called abs () in our class.

In the above example, we have defined a class called Complex that represents a complex number with a real and imaginary part. We have then defined the abs () method to return the magnitude of the complex number, which is calculated using the Pythagorean theorem. We can now use the abs() function with objects of this class to determine their magnitude.

  • Printing Your Objects Prettily Using str()

The str() function is used to convert an object to a string. To make our own objects work with str(), we can define a method called str () in our class.

In the above example, we have defined a class called Person that stores a name and an age. We have then defined the str () method to return a string representation of the Person object. We can now use the str() function with objects of this class to convert them to a string.

  • Representing Your Objects Using repr()

The repr() function is used to obtain a string representation of an object that can be used to recreate the object. To make our own objects work with repr(), we can define a method called repr () in our class.

Examples of Operator Overloading in Python

A. Explanation of real-world use cases for operator overloading:

Operator overloading can be used in many real-world scenarios to make code more readable and intuitive. Let’s explore some examples of how operator overloading can be useful:

  • Overloading “<” Operator:

In some cases, it may be useful to compare objects of a custom class using the “<” operator. For example, let’s say we have a class “Rectangle” that represents a rectangle with a certain height and width. We may want to compare two rectangles to see which one has a greater area. We can achieve this by overloading the “<” operator in the Rectangle class.

  • Overloading “+” Operator:

We can also overload the “+” operator to perform custom operations on objects of a class. For example, let’s say we have a class “Fraction” that represents a fraction with a numerator and denominator. We may want to add two fractions together to get a new fraction. We can overload the “+” operator in the Fraction class to perform this operation.

  • Overloading Comparison Operators:

In some cases, we may want to compare objects of a custom class using comparison operators such as “>”, “<=”, etc. For example, let’s say we have a class “Person” that represents a person with a certain age. We may want to compare two people to see who is older. We can overload the comparison operators in the Person class to perform this operation.

  • Overloading Equality Operator:

We can also overload the equality operator “==” to perform custom comparisons on objects of a class. For example, let’s say we have a class “Point” that represents a point in 2D space with an x and y coordinate. We may want to compare two points to see if they are the same point. We can overload the equality operator in the Point class to perform this comparison.

B. Example code snippets:

2. Overloading “+” Operator:

In this example, we overload the less-than operator (<) to compare the rectangles based on their area. The __lt__ method is called when the < operator is used with rectangle objects. The method returns True if the area of the current rectangle is less than the area of the other rectangle.

In this example, we overload the equality operator (==) to compare the students based on their name and age. The __eq__ method is called when the == operator is used with student objects. The method returns True if the name and age of the current student are equal to the name and age of the other student.

Magic Methods for Operator Overloading in Python

A. Explanation of magic methods and their usage for operator overloading: In Python, operators are implemented as special methods, called “magic methods” or “dunder methods” (short for “double underscore” methods), that have special names enclosed in double underscores. By defining these methods in our classes, we can customize how operators behave with our objects, which is known as operator overloading.

Here are some common magic methods for operator overloading:

  • Binary Operators:
  • __add__(self, other): Implement the addition operator +.
  • __sub__(self, other): Implement the subtraction operator -.
  • __mul__(self, other): Implement the multiplication operator *.
  • __truediv__(self, other): Implement the true division operator /.
  • __floordiv__(self, other): Implement the floor division operator //.
  • __mod__(self, other): Implement the modulo operator %.
  • __pow__(self, other[, modulo]): Implement the power operator **.
  • Comparison Operators:
  • __eq__(self, other): Implement the equality operator ==.
  • __ne__(self, other): Implement the not equal operator !=.
  • __lt__(self, other): Implement the less than operator <.
  • __le__(self, other): Implement the less than or equal operator <=.
  • __gt__(self, other): Implement the greater than operator >.
  • __ge__(self, other): Implement the greater than or equal operator >=.
  • Assignment Operators:
  • __iadd__(self, other): Implement the in-place addition operator +=.
  • __isub__(self, other): Implement the in-place subtraction operator -=.
  • __imul__(self, other): Implement the in-place multiplication operator *=.
  • __itruediv__(self, other): Implement the in-place true division operator /=.
  • __ifloordiv__(self, other): Implement the in-place floor division operator //=.
  • __imod__(self, other): Implement the in-place modulo operator %=.
  • _ _ipow__(self, other[, modulo]): Implement the in-place power operator **=.
  • Unary Operators:
  • __neg__(self): Implement the negation operator -.
  • __pos__(self): Implement the unary plus operator +.
  • __abs__(self): Implement the absolute value operator abs().
  • __ invert__(self): Implement the bitwise inversion operator ~.
  • Mathematical Operators:
  • __round__(self[, n]): Implement the round() function.
  • __floor__(self): Implement the math.floor() function.
  • __ceil__(self): Implement the math.ceil() function.
  • __trunc__(self): Implement the math.trunc() function.

Binary operators include addition (+), subtraction (-), multiplication (*), division (/), modulo (%), etc. The following is an example of overloading the “+” operator for a custom class:

Comparison operators include greater than (>), less than (<), equal to (==), etc. The following is an example of overloading the “>” operator for a custom class:

  • Assignment Operators :

Assignment operators include +=, -=, *=, etc. The following is an example of overloading the “+=” operator for a custom class:

Unary operators include negation (-), inversion (~), etc. The following is an example of overloading the “-” operator for a custom class:

Mathematical operators include pow ( ), floor division (//), etc. The following is an example of overloading the “ ” operator for a custom class:

In this blog post, we have discussed the concept of operator overloading in Python. We have explained the importance of operator overloading and its usage in Python. We have also provided a brief overview of the topics covered in this article.

We have discussed how to overload operators in Python using magic methods and provided code snippets for various types of operators such as binary, comparison, assignment, unary, and mathematical operators. We have also explained the mechanism behind operator overloading and the advantages of using operator overloading in Python.

Furthermore, we have discussed the need for operator overloading and provided examples of real-world use cases for operator overloading. Finally, we have explained the magic methods used for operator overloading and provided code snippets for each of them.

Overall, operator overloading is a powerful tool in Python that allows us to customize the behavior of operators for our own classes. By overloading operators, we can make our code more readable, efficient, and easier to maintain.

What is operator overloading in Python?

Operator overloading is a technique in Python that allows the use of built-in operators for user-defined objects. This means that the behavior of an operator can be changed depending on the type of operands used in the operation. By overloading an operator, it becomes possible to perform operations that were not originally supported by the operator. For example, by overloading the + operator, we can concatenate two strings or add two numbers stored in custom objects.

What is operator overloading with example?

One example of operator overloading can be seen with the == operator. This operator is used for comparing two values for equality. However, it can also be used to compare two objects of a user-defined class. Consider the following example:

class Employee:     def __init__(self, id, name):         self.id = id         self.name = name     def __eq__(self, other):         return self.id == other.id e1 = Employee(1, "John") e2 = Employee(1, "Jack") if e1 == e2:     print("They are the same employee") else:     print("They are different employees")

In the above example, we have defined a custom class “Employee” with two attributes “id” and “name”. We have also defined the eq method to overload the == operator for this class. This method takes two arguments, self and other, which represent the two objects being compared. The method compares the id attributes of the two objects and returns True if they are the same.

What is operator overloading with syntax?

In Python, operator overloading is achieved by defining special methods that start and end with two underscores. These methods are also known as “magic methods” or “dunder methods” (short for “double underscore”). Here is a list of some of the common dunder methods used for operator overloading in Python:

__add__(self, other) - Overloads the + operator for addition __sub__(self, other) - Overloads the - operator for subtraction __mul__(self, other) - Overloads the * operator for multiplication __truediv__(self, other) - Overloads the / operator for division __mod__(self, other) - Overloads the % operator for modulus __lt__(self, other) - Overloads the < operator for less than comparison __le__(self, other) - Overloads the <= operator for less than or equal to comparison __eq__(self, other) - Overloads the == operator for equality comparison __ne__(self, other) - Overloads the != operator for inequality comparison __gt__(self, other) - Overloads the > operator for greater than comparison __ge__(self, other) - Overloads the >= operator for greater than or equal to comparison

The syntax for defining an operator overload is:

class MyClass:     def __add__(self, other):         # code to define the behavior of the + operator         pass

In this example, we have defined the add method for a custom class “MyClass”. This method takes two arguments, self and other, which represent the two objects being added. The method should return a new object that represents the result of the addition. Note that the pass statement is just a placeholder and should be replaced with actual code. The same syntax can be used to define other dunder methods for operator overloading.

overload assignment operator python

Reviewed by

Share article on

tutor Pic

Learn Operator Overloading in Python

Avatar

Kenneth Love writes on October 27, 2014

Operator Overloading in Python

Python is an interesting language. It’s meant to be very explicit and easy to work with. But what happens when how you want or need to work with Python isn’t just what the native types expose? Well, you can build classes and give those classes attributes or methods that let you use them, but then you end up having to call methods instead of being able to just add items together where it makes sense.

But what if you could just add them together? What if your Area class instances could just be added together to make a larger area? Well, thankfully, you can. This practice is called Operator Overloading because you’re overloading, or overwriting, how operators work. By “operator”, I mean symbols like + , - , and * .

Remember back in Object-Oriented Python when we overloaded __init__() to change how our classes initialized themselves? And we overrode __str__() to change how our class instances became strings? Well, we’re going to do the same thing in this article with __add__ and some friends. This controls how instances add themselves together and with others. OK, let’s get started.

Many of us here at Treehouse like to read and I think it would be neat to have a way to measure the books we’ve read. Let’s ignore the fact that several services already exist to do this very thing. I want to do it locally and in Python. Obviously I should start with a Book class.

Nothing here that we didn’t cover in Object-Oriented Python . We make an instance and set some attributes based on the passed-in values. We also gave our class a __str__ method so it’ll give us the title when we turn it into a string.

What I want to be able to do, though, is something like:

And get back 1152 (also, I had no idea I read so many books with similar page numbers). Currently, that’s not going to work. Python is going to give me an error about "TypeError: unsupported operand type(s) for +: 'int' and 'Book'" . That’s because our Book class has no idea what to do with a plus sign. Let’s fix that.

Check out:  Should I learn HTML Before Python?

Reverse Adding

So the sum() function in Python is pretty swell. It takes a list of numbers and adds them all together. So if you have a bunch of, say, baseball inning scores, you can add them together in one method without having to have a counter variable or anything like that.

But , sum() does something you probably don’t expect. It starts with 0 and then adds the first itme in the list to that. So if the first item doesn’t know how to add itself to 0, Python fails. But before it fails, Python tries to do a reversed add with the operators.

Basically, remember how 2 + 5 and 5 + 2 are the same thing due to the commutative property of addition? Python takes advantage of that and swaps the operators. So instead of 0 + Book , it tries Book + 0 . 0 + Book won’t work because the int class has no idea how to add itself to books. Our Book class can’t do the reverse add yet but we can give it the ability to.

This method has the best name in the 1990s. We have to override __radd__ , or “reverse add”.

OK, let’s try it.

But what if we want to add two Book instances together directly? If we do:

from our above example, we get another TypeError about + being unsupported for the Book type. Well, yeah, we told Python how to add them in reverse, but no matter how Python tries to put these together, one of them has to be in front, so __radd__ isn’t being used.

Related Reading:  Python for Beginners: Let’s play a/an [adjective] game

Time for regular adding, then. As you might have guessed, we override the __add__ method.

And now we can add books together:

Well, adding Book instances together seems to be pretty well sewn up. But what if we want to compare books to each other? Let’s override a few more methods so we can use < , > , and friends.

Comparative Literature

There’s a handful of methods we have to override to implement the comparison operators in our class. Let’s just do them all at once.

This works fine for < , > , == , and != , but blows up on <= and >= because we haven’t said what to compare against on other in those examples. We’ll update those two to automatically compare against .pages but we should also make them so they make sure it’s a valid comparison.

Yes, this is more work but it makes our code smarter. If we’re comparing two Book instances, we’ll use their pages attributes. If not, but we’re comparing against a number, we’ll compare that like normal. Then, finally, we’ll return a NotImplemented error for anything else. Let’s try it out.

Great! Now we can add books together to get total page counts and we can compare books to each other.

Learn more Python tools: Python One Line For Loops [Tutorial]

That’s just the beginning

If we wanted to, there are several more methods that it would make sense to override on our classes. We might want to make our Book class give back the page count when it’s turned into an int . We’d do this with the __int__ method. Or maybe we want to be able to increase or decrease page counts with += and -= . We’d do that by overriding __iadd__ and __isub__ . To see the entire list of magic methods that can be overridden, check the Python documentation . I’ve also posted the code from this article. See you next time!

Check out my Python courses at Treehouse, and try out the Treehouse 7-day free trial .

Photo from Loughborough University Library .

GET STARTED NOW

Learning with Treehouse for only 30 minutes a day can teach you the skills needed to land the job that you've been dreaming about.

  • object-oriented

7 Responses to “Operator Overloading in Python”

Can you explain why >= and <= don't work? You wrote, "Because we haven’t said what to compare against on other in those examples," but you didn't do that with , !=, or == and yet they work without explicitly comparing self.pages to other.pages.

yeah, this thing is riddled with mistakes. dude you need a proofreader.

Under the section “Adding”, the definition of__add__ should be

def __add__(self, other): return self.pages + other.pages

yeah i noticed that too and was confused for a while and figured it must’ve been a typo. your comment confirmed it to me. these tutorials need to be very carefully proofread because any mistake can make it very confusing for a novice.

Great tutorial! Just wondering, why is it different for `=`? Why you need to do type inspection for them but not for others (“ etc)?

Hello, Python starter here!

Just wondering, does one have to overload both the add and reverse add methods to fully integrate adding functionality?

Hey Thomas,

You don’t *have* to overload both but most of the time you’ll want to. __radd__ lets Python know how to add things when the second type doesn’t match its expectations and this happens more often than you think. The good thing is, most of the time, __add__ and __radd__ are very similar, often just inverses of each other!

Leave a Reply

You must be logged in to post a comment.

man working on his laptop

Are you ready to start learning?

woman working on her laptop

  • Python Basics
  • Interview Questions
  • Python Quiz
  • Popular Packages
  • Python Projects
  • Practice Python
  • AI With Python
  • Learn Python3
  • Python Automation
  • Python Web Dev
  • DSA with Python
  • Python OOPs
  • Dictionaries

Python Operators

Precedence and associativity of operators in python.

  • Python Arithmetic Operators
  • Difference between / vs. // operator in Python
  • Python - Star or Asterisk operator ( * )
  • What does the Double Star operator mean in Python?
  • Division Operators in Python
  • Modulo operator (%) in Python
  • Python Logical Operators
  • Python OR Operator
  • Difference between 'and' and '&' in Python
  • not Operator in Python | Boolean Logic

Ternary Operator in Python

  • Python Bitwise Operators

Python Assignment Operators

Assignment operators in python.

  • Walrus Operator in Python 3.8
  • Increment += and Decrement -= Assignment Operators in Python
  • Merging and Updating Dictionary Operators in Python 3.9
  • New '=' Operator in Python3.8 f-string

Python Relational Operators

  • Comparison Operators in Python
  • Python NOT EQUAL operator
  • Difference between == and is operator in Python
  • Chaining comparison operators in Python
  • Python Membership and Identity Operators
  • Difference between != and is not operator in Python

In Python programming, Operators in general are used to perform operations on values and variables. These are standard symbols used for logical and arithmetic operations. In this article, we will look into different types of Python operators. 

  • OPERATORS: These are the special symbols. Eg- + , * , /, etc.
  • OPERAND: It is the value on which the operator is applied.

Types of Operators in Python

  • Arithmetic Operators
  • Comparison Operators
  • Logical Operators
  • Bitwise Operators
  • Assignment Operators
  • Identity Operators and Membership Operators

Python Operators

Arithmetic Operators in Python

Python Arithmetic operators are used to perform basic mathematical operations like addition, subtraction, multiplication , and division .

In Python 3.x the result of division is a floating-point while in Python 2.x division of 2 integers was an integer. To obtain an integer result in Python 3.x floored (// integer) is used.

Example of Arithmetic Operators in Python

Division operators.

In Python programming language Division Operators allow you to divide two numbers and return a quotient, i.e., the first number or number at the left is divided by the second number or number at the right and returns the quotient. 

There are two types of division operators: 

Float division

  • Floor division

The quotient returned by this operator is always a float number, no matter if two numbers are integers. For example:

Example: The code performs division operations and prints the results. It demonstrates that both integer and floating-point divisions return accurate results. For example, ’10/2′ results in ‘5.0’ , and ‘-10/2’ results in ‘-5.0’ .

Integer division( Floor division)

The quotient returned by this operator is dependent on the argument being passed. If any of the numbers is float, it returns output in float. It is also known as Floor division because, if any number is negative, then the output will be floored. For example:

Example: The code demonstrates integer (floor) division operations using the // in Python operators . It provides results as follows: ’10//3′ equals ‘3’ , ‘-5//2’ equals ‘-3’ , ‘ 5.0//2′ equals ‘2.0’ , and ‘-5.0//2’ equals ‘-3.0’ . Integer division returns the largest integer less than or equal to the division result.

Precedence of Arithmetic Operators in Python

The precedence of Arithmetic Operators in Python is as follows:

  • P – Parentheses
  • E – Exponentiation
  • M – Multiplication (Multiplication and division have the same precedence)
  • D – Division
  • A – Addition (Addition and subtraction have the same precedence)
  • S – Subtraction

The modulus of Python operators helps us extract the last digit/s of a number. For example:

  • x % 10 -> yields the last digit
  • x % 100 -> yield last two digits

Arithmetic Operators With Addition, Subtraction, Multiplication, Modulo and Power

Here is an example showing how different Arithmetic Operators in Python work:

Example: The code performs basic arithmetic operations with the values of ‘a’ and ‘b’ . It adds (‘+’) , subtracts (‘-‘) , multiplies (‘*’) , computes the remainder (‘%’) , and raises a to the power of ‘b (**)’ . The results of these operations are printed.

Note: Refer to Differences between / and // for some interesting facts about these two Python operators.

Comparison of Python Operators

In Python Comparison of Relational operators compares the values. It either returns True or False according to the condition.

= is an assignment operator and == comparison operator.

Precedence of Comparison Operators in Python

In Python, the comparison operators have lower precedence than the arithmetic operators. All the operators within comparison operators have the same precedence order.

Example of Comparison Operators in Python

Let’s see an example of Comparison Operators in Python.

Example: The code compares the values of ‘a’ and ‘b’ using various comparison Python operators and prints the results. It checks if ‘a’ is greater than, less than, equal to, not equal to, greater than, or equal to, and less than or equal to ‘b’ .

Logical Operators in Python

Python Logical operators perform Logical AND , Logical OR , and Logical NOT operations. It is used to combine conditional statements.

Precedence of Logical Operators in Python

The precedence of Logical Operators in Python is as follows:

  • Logical not
  • logical and

Example of Logical Operators in Python

The following code shows how to implement Logical Operators in Python:

Example: The code performs logical operations with Boolean values. It checks if both ‘a’ and ‘b’ are true ( ‘and’ ), if at least one of them is true ( ‘or’ ), and negates the value of ‘a’ using ‘not’ . The results are printed accordingly.

Bitwise Operators in Python

Python Bitwise operators act on bits and perform bit-by-bit operations. These are used to operate on binary numbers.

Precedence of Bitwise Operators in Python

The precedence of Bitwise Operators in Python is as follows:

  • Bitwise NOT
  • Bitwise Shift
  • Bitwise AND
  • Bitwise XOR

Here is an example showing how Bitwise Operators in Python work:

Example: The code demonstrates various bitwise operations with the values of ‘a’ and ‘b’ . It performs bitwise AND (&) , OR (|) , NOT (~) , XOR (^) , right shift (>>) , and left shift (<<) operations and prints the results. These operations manipulate the binary representations of the numbers.

Python Assignment operators are used to assign values to the variables.

Let’s see an example of Assignment Operators in Python.

Example: The code starts with ‘a’ and ‘b’ both having the value 10. It then performs a series of operations: addition, subtraction, multiplication, and a left shift operation on ‘b’ . The results of each operation are printed, showing the impact of these operations on the value of ‘b’ .

Identity Operators in Python

In Python, is and is not are the identity operators both are used to check if two values are located on the same part of the memory. Two variables that are equal do not imply that they are identical. 

Example Identity Operators in Python

Let’s see an example of Identity Operators in Python.

Example: The code uses identity operators to compare variables in Python. It checks if ‘a’ is not the same object as ‘b’ (which is true because they have different values) and if ‘a’ is the same object as ‘c’ (which is true because ‘c’ was assigned the value of ‘a’ ).

Membership Operators in Python

In Python, in and not in are the membership operators that are used to test whether a value or variable is in a sequence.

Examples of Membership Operators in Python

The following code shows how to implement Membership Operators in Python:

Example: The code checks for the presence of values ‘x’ and ‘y’ in the list. It prints whether or not each value is present in the list. ‘x’ is not in the list, and ‘y’ is present, as indicated by the printed messages. The code uses the ‘in’ and ‘not in’ Python operators to perform these checks.

in Python, Ternary operators also known as conditional expressions are operators that evaluate something based on a condition being true or false. It was added to Python in version 2.5. 

It simply allows testing a condition in a single line replacing the multiline if-else making the code compact.

Syntax :   [on_true] if [expression] else [on_false] 

Examples of Ternary Operator in Python

The code assigns values to variables ‘a’ and ‘b’ (10 and 20, respectively). It then uses a conditional assignment to determine the smaller of the two values and assigns it to the variable ‘min’ . Finally, it prints the value of ‘min’ , which is 10 in this case.

In Python, Operator precedence and associativity determine the priorities of the operator.

Operator Precedence in Python

This is used in an expression with more than one operator with different precedence to determine which operation to perform first.

Let’s see an example of how Operator Precedence in Python works:

Example: The code first calculates and prints the value of the expression 10 + 20 * 30 , which is 610. Then, it checks a condition based on the values of the ‘name’ and ‘age’ variables. Since the name is “ Alex” and the condition is satisfied using the or operator, it prints “Hello! Welcome.”

Operator Associativity in Python

If an expression contains two or more operators with the same precedence then Operator Associativity is used to determine. It can either be Left to Right or from Right to Left.

The following code shows how Operator Associativity in Python works:

Example: The code showcases various mathematical operations. It calculates and prints the results of division and multiplication, addition and subtraction, subtraction within parentheses, and exponentiation. The code illustrates different mathematical calculations and their outcomes.

To try your knowledge of Python Operators, you can take out the quiz on Operators in Python . 

Python Operator Exercise Questions

Below are two Exercise Questions on Python Operators. We have covered arithmetic operators and comparison operators in these exercise questions. For more exercises on Python Operators visit the page mentioned below.

Q1. Code to implement basic arithmetic operations on integers

Q2. Code to implement Comparison operations on integers

Explore more Exercises: Practice Exercise on Operators in Python

Please Login to comment...

Similar reads.

  • python-basics
  • Python-Operators

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. Operator Overloading in Python

    overload assignment operator python

  2. Operator Overloading in Python (Polymorphism)

    overload assignment operator python

  3. Python OOP Tutorials

    overload assignment operator python

  4. What is Operator Overloading in Python (with Examples)

    overload assignment operator python

  5. Python Tutorial #48

    overload assignment operator python

  6. Python Operator Overloading

    overload assignment operator python

VIDEO

  1. Assignment

  2. Python Assignment Operator #coding #assignmentoperators #phython

  3. Assignment Operator in Python Lec 7

  4. python assignment operator

  5. Assignment & Relational Operator

  6. 50 Operator Overloading in Python

COMMENTS

  1. Is it possible to overload Python assignment?

    101. The way you describe it is absolutely not possible. Assignment to a name is a fundamental feature of Python and no hooks have been provided to change its behavior. However, assignment to a member in a class instance can be controlled as you want, by overriding .__setattr__(). class MyClass(object):

  2. Operator Overloading in Python

    Operator Overloading in Python. Operator Overloading means giving extended meaning beyond their predefined operational meaning. For example operator + is used to add two integers as well as join two strings and merge two lists. It is achievable because '+' operator is overloaded by int class and str class. You might have noticed that the ...

  3. How to Emulate Assignment Operator Overloading in Python?

    0. You can't overload assignment. It's not an operator. You would be better off here just constructing the value in the object constructor. class Example(object): def __init__(self,myname, myage): self.name = String(myname) self.age = Integer(myage) However in this case I don't see why you can't just use the built-in str and int.

  4. Python Operator Overloading

    Introduction to the Python operator overloading. Suppose you have a 2D point class with x and y coordinate attributes: ... the inplace operator performs the updates on the original objects directly. The assignment is not necessary. Python also provides you with a list of special methods that allows you to overload the inplace operator: Operator ...

  5. Python's Assignment Operator: Write Robust Assignments

    To create a new variable or to update the value of an existing one in Python, you'll use an assignment statement. This statement has the following three components: A left operand, which must be a variable. The assignment operator ( =) A right operand, which can be a concrete value, an object, or an expression.

  6. Operator and Function Overloading in Custom Python Classes

    Objects of our class will support a variety of built-in functions and operators, making them behave very similar to the built-in complex numbers class: Python. from math import hypot, atan, sin, cos class CustomComplex: def __init__(self, real, imag): self.real = real self.imag = imag.

  7. Python Assignment Operator Overloading

    Python - Assignment Operator Overloading. Assignment operator is a binary operator which means it requires two operand to produce a new value. Following is the list of assignment operators and corresponding magic methods that can be overloaded in Python. ... In the example below, assignment operator (+=) is overloaded. When it is applied with a ...

  8. Python Operator Overloading (With Examples)

    Python does not limit operator overloading to arithmetic operators only. We can overload comparison operators as well. Here's an example of how we can overload the < operator to compare two objects the Person class based on their age: class Person: def __init__(self, name, age): self.name = name. self.age = age.

  9. Operator Overloading in Python

    To overload the ' + ' operator, we will use the __add__ magic method. Output: Here we have defined the __add()__ method and passed the Coordinates object and got the sum of the coordinates as the result. This is how we can define the magic methods and can also change their behavior according to our needs. In python whenever we use ...

  10. Operator Overloading in Python

    Operator Overloading is the phenomenon of giving alternate/different meaning to an action performed by an operator beyond their predefined operational function. Operator overloading is also called Operator Ad-hoc Polymorphism. Python operators work for built-in classes. But the same operator expresses differently with different types.

  11. Python Operator Overloading

    Operator Overloading in Python. Python gives us the ability to modify the operation of an operator when used for specific operands. Every time we use an operator, Python internally invokes a magic method. In the case of +, Python invokes the __add__ method.

  12. What is Operator Overloading in Python (with Examples)

    Overloading Assignment Operators in Python. In Python we can overload assignment operators like arithmetic operators. When we use any assignment operator with any object then which special method will be called is shown in a table below. Expression During Execution ; obj1 += obj2: obj1.__iadd__(obj2)

  13. operator overloading in python

    Vice versa, in Python = (plain assignment) is not an operator, so you cannot overload that, while in C++ it is an operator and you can overload it. << is an operator, and can be overloaded, in both languages -- that's how << and >>, while not losing their initial connotation of left and right shifts, also became I/O formatting operators in C++ ...

  14. Python Operator Overloading

    Python operator overloading means giving another meaning to a common operator in a different context. For example, the + operator is used to adding up two integers. But it can also be overloaded to support adding two custom objects. Operator overloading happens by providing an implementation to a special double underscore method in a class.

  15. Python Operator Overloading

    Operator overloading in Python. Operators are used in Python to perform specific operations on the given operands. The operation that any particular operator will perform on any predefined data type is already defined in Python. Each operator can be used in a different way for different types of operands. For example, + operator is used for ...

  16. Python Operator Overloading And Magic Methods

    Operator Overloading In Python. Basically, operator overloading means giving extended meaning beyond their predefined operational meaning. For example, a + operator is used to add the numeric values as well as to concatenate the strings. That's because + is overloaded for int class and str class. But we can give extra meaning to this ...

  17. Operator Overloading In Python

    Operator overloading is a powerful feature in Python that allows us to redefine the behavior of operators for custom classes. It provides enhanced readability, customized behaviors, and code reusability. By leveraging operator overloading effectively, we can create more expressive and intuitive code, improving the overall design and ...

  18. Operator Overloading in Python

    What is Operator Overloading in Python? Operator overloading is a feature of Python that lets you use the same operator for more than one task.It lets programmers change the way an operator works by letting them define their own implementation for a certain operator for a certain class or object.The term "magic methods" refers to functions or techniques that are used to overload the operator.

  19. Python Operator Overloading Tutorial

    What is Python Operator Overloading? Operator overloading in Python is a fascinating feature that allows the same operator to have different meanings based on the context. It's like a chameleon changing its colors according to its surroundings. But instead, here, the operator changes its function depending on the operands.

  20. Operator Overloading in Python [Article]

    Well, thankfully, you can. This practice is called Operator Overloading because you're overloading, or overwriting, how operators work. By "operator", I mean symbols like +, -, and *. Remember back in Object-Oriented Python when we overloaded __init__() to change how our classes initialized themselves?

  21. Python Operators

    To try your knowledge of Python Operators, you can take out the quiz on Operators in Python. Python Operator Exercise Questions. Below are two Exercise Questions on Python Operators. We have covered arithmetic operators and comparison operators in these exercise questions. For more exercises on Python Operators visit the page mentioned below. Q1.

  22. operator overloading

    I know about the __add__ method to override plus, but when I use that to override +=, I end up with one of two problems:. if __add__ mutates self, then. z = x + y will mutate x when I don't really want x to be mutated there. if __add__ returns a new object, then. tmp = z z += x z += y tmp += w return z will return something without w since z and tmp point to different objects after z += x is ...