• Free Python 3 Tutorial
  • Control Flow
  • Exception Handling
  • Python Programs
  • Python Projects
  • Python Interview Questions
  • Python Database
  • Data Science With Python
  • Machine Learning with Python
  • Statement, Indentation and Comment in Python
  • Python | Set 2 (Variables, Expressions, Conditions and Functions)
  • Global and Local Variables in Python
  • Type Conversion in Python
  • Private Variables in Python
  • __name__ (A Special variable) in Python
  • Taking input in Python
  • Taking multiple inputs from user in Python
  • Python | Output using print() function
  • Python end parameter in print()
  • Python | Output Formatting
  • Python Operators
  • Ternary Operator in Python

Operator Overloading in Python

  • Python | a += b is not always a = a + b
  • Difference between == and is operator in Python
  • Python | Set 3 (Strings, Lists, Tuples, Iterations)
  • Python String
  • Python Lists
  • Python Tuples
  • Python Sets
  • Dictionaries in Python
  • Python Arrays
  • Python If Else Statements - Conditional Statements
  • Loops in Python - For, While and Nested Loops

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 same built-in operator or function shows different behavior for objects of different classes, this is called Operator Overloading . 

How to overload the operators in Python?  

Consider that we have two objects which are a physical representation of a class (user-defined data type) and we have to add two objects with binary ‘+’ operator it throws an error, because compiler don’t know how to add two objects. So we define a method for an operator and that process is called operator overloading. We can overload all existing operators but we can’t create a new operator. 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.

Overloading binary + operator in Python:  

When we use an operator on user-defined data types then automatically a special function or magic function associated with that operator is invoked. Changing the behavior of operator is as simple as changing the behavior of a method or function. You define methods in your class and operators work according to that behavior defined in methods. When we use + operator, the magic method __add__ is automatically invoked in which the operation for + operator is defined. Thereby changing this magic method’s code, we can give extra meaning to the + operator. 

How Does the Operator Overloading Actually work?

Whenever you change the behavior of the existing operator through operator overloading, you have to redefine the special function that is invoked automatically when the operator is used with the objects. 

For Example: 

Code 1:   

Here, We defined the special function “ __add__( ) ”  and when the objects ob1 and ob2 are coded as “ ob1 + ob2 “, the special function is automatically called as ob1.__add__(ob2) which simply means that ob1 calls the __add__( ) function with ob2 as an Argument and It actually means A .__add__(ob1, ob2) . Hence, when the Binary operator is overloaded, the object before the operator calls the respective function with object after operator as parameter.

Code 2: 

Overloading comparison operators in Python :   

Overloading equality and less than operators:  

Python magic methods or special functions for operator overloading

Binary operators :, comparison operators:.

Assignment Operators:

Unary Operators:

Note: It is not possible to change the number of operands of an operator. For example: If we can not overload a unary operator as a binary operator. The following code will throw a syntax error.

operator overloading on Boolean values:  

In Python, you can overload the Boolean operators and, or, and not by defining the __and__, __or__, and __not__ special methods in your class.

Here’s an example of how to overload the and operator for a custom class:

Explanation:

In this example, we define a MyClass that has a single attribute value, which is a boolean. We then overload the & operator by defining the __and__ method to perform a logical and operation on the value attribute of two MyClass instances.

When we call a & b, the __and__ method is called with a as the first argument and b as the second argument. The method returns a new instance of MyClass with a value attribute that is the logical and of a.value and b.value.

Note that Python also provides built-in boolean operators that can be used with any object. For example, you can use the bool() function to convert any object to a boolean value, and the all() and any() functions to perform logical and and or operations on a sequence of boolean values. Overloading the boolean operators in a custom class can be useful to provide a more natural syntax and semantics for your class.

Advantages:

Overloading boolean operators in a custom class can provide several advantages, including:

  • Improved readability: By overloading boolean operators, you can provide a more natural syntax and semantics for your class that makes it easier to read and understand.
  • Consistency with built-in types: Overloading boolean operators can make your class behave more like built-in types in Python, which can make it easier to use and integrate with other code.
  • Operator overloading: Overloading boolean operators is an example of operator overloading in Python, which can make your code more concise and expressive by allowing you to use familiar operators to perform custom operations on your objects.
  • Custom behavior: Overloading boolean operators can allow you to define custom behavior for your class that is not available in built-in types or other classes.
  • Enhanced functionality: By overloading boolean operators, you can add new functionality to your class that was not available before, such as the ability to perform logical and or or operations on instances of your class.

Overall, overloading boolean operators in a custom class can make your code more readable, consistent, concise, expressive, and functional. However, it’s important to use operator overloading judiciously and only when it makes sense for the semantics of your class.

Please Login to comment...

Similar reads.

author

  • Python-Operators
  • CBSE Exam Format Changed for Class 11-12: Focus On Concept Application Questions
  • 10 Best Waze Alternatives in 2024 (Free)
  • 10 Best Squarespace Alternatives in 2024 (Free)
  • Top 10 Owler Alternatives & Competitors in 2024
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • 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

Home » Python OOP » Python Operator Overloading

Python Operator Overloading

Summary : in this tutorial, you’ll learn Python operator overloading and how to use it to make your objects work with built-in operators.

Introduction to the Python operator overloading

Suppose you have a 2D point class with x and y coordinate attributes :

To add two Point2D objects, you can define an add() method as follows:

The add() method raises an error if the point is not an instance of the Point2D class. Otherwise, it returns a new Point2D object whose x and y coordinates are the sums of x and y coordinates of two points.

The following creates two instances of the Point2D class and use the add() method to add two points:

This code works perfectly fine. But Python has a better way to implement it. Instead of using the add() method, you can use the built-in operator (+) like this:

When you use the + operator on the Point2D object, Python will call the special method __add__() on the object. The following calls are equivalent:

The __add__() method must return a new instance of the Point2D object.

The ability to use the built-in operator ( + ) on a custom type is known as operator overloading.

The following shows the Point2D class that implements the __add__() special operator to support the + operator:

Special methods for operator overloading

The following shows the operators with their corresponding special methods:

For example, you can implement the __sub__() method in the Point2D to support subtraction ( - ) of two points:

Overloading inplace opeators

Some operators have the inplace version. For example, the inplace version of + is +=.

For the immutable type like a tuple , a string, a number, the inplace operators perform calculations and don’t assign the result back to the input object.

For the mutable type, 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:

Let’s take an example of overloading the += operator.

Suppose you have a cart object and you want to add an item to the cart. To do you, you can define an add() method to the Cart class and use it like this:

Alternatively, you can implement the += operator in the Cart class. It allows you to add an item to the cart as follows:

To support the += operator, you need to implement the __iadd__ special method in the Cart class.

First, define the Item class that has three attributes name, quantity, and price. Also, it has an amount property that returns the subtotal of the item:

Second, define the Cart class that implements the __iadd__ method:

In the __iadd__ method, we raise a ValueError if the item is not an instance of the Item class. Otherwise, we add the item to the items list attribute.

The total property returns the sum of all items.

The __str__ method returns the string 'The cart is empty' if the cart has no item. Otherwise, it returns a string that contains all items separated by a newline.

Third, use the += operator to add an item to the cart:

  • Opeartor overloading allows a class to use built-in operators.

Learn Python practically and Get Certified .

Popular Tutorials

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

  • Getting Started
  • Keywords and Identifier
  • Python Comments
  • Python Variables
  • Python Data Types
  • Python Type Conversion
  • Python I/O and Import

Python Operators

  • Python Namespace

Python Flow Control

  • Python if...else
  • Python for Loop
  • Python while Loop
  • Python break and continue
  • Python Pass

Python Functions

  • Python Function
  • Function Argument
  • Python Recursion
  • Anonymous Function
  • Global, Local and Nonlocal
  • Python Global Keyword
  • Python Modules
  • Python Package

Python Datatypes

  • Python Numbers
  • Python List
  • Python Tuple
  • Python String
  • Python Dictionary

Python Files

  • Python File Operation
  • Python Directory
  • Python Exception
  • Exception Handling
  • User-defined Exception

Python Object & Class

  • Classes & Objects
  • Python Inheritance
  • Multiple Inheritance
  • Operator Overloading

Python Advanced Topics

  • Python Iterator
  • Python Generator
  • Python Closure
  • Python Decorators
  • Python Property
  • Python RegEx

Python Date and time

  • Python datetime Module
  • Python datetime.strftime()
  • Python datetime.strptime()
  • Current date & time
  • Get current time
  • Timestamp to datetime
  • Python time Module
  • Python time.sleep()

Python Tutorials

Precedence and Associativity of Operators in Python

Python dir()

  • Python object()

Python Lists Vs Tuples

  • Polymorphism in Python

Python Operator Overloading

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

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:

overloading assignment operator in python

Recommended Articles

Leave a reply cancel reply.

Algoryst's Corner

Operator Overloading In Python

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 .

You might also like...

Iterators vs generator vs classic coroutines in python, generic types, covariance and overloading signatures in python, advanced guide to inheritance and subclassing in python, different flavors of protocols in python, supporting sequence protocol and magic methods in python.

overloading assignment operator in python

Hiring? Flexiple helps you build your dream team of  developers   and  designers .

Operator Overloading In Python

Harsh Pandey

Harsh Pandey

Last updated on 19 Mar 2024

Operator overloading in Python is a fascinating and powerful feature that allows custom objects to interact with Python's built-in operators in a way that is intuitive and elegant. This blog demystifies the concept, showing how it can be used to make your classes more Pythonic and your code more readable.

Introduction To Operator Overloading

In Python, everything is an object, and operations like addition (+), subtraction (-), or comparison (==) are just syntactic sugar for calling special methods like __add__ , __sub__ , or __eq__ . This is where operator overloading comes into play. By defining these special methods in your class, you can specify what should happen when they are used with your class's instances.

Why Use Operator Overloading?

The main reason to use operator overloading is to make your objects behave like the built-in types. This makes your code more intuitive and easier to read. For instance, if you have a class that represents a mathematical concept like a vector, it makes sense to use + to add two vectors rather than having a separate method.

How To Overload Operators In Python?

To overload operators in Python, you define special methods in your class that are automatically invoked when you use operators like +, -, *, etc. These methods are known as magic methods and have double underscores (__) at the beginning and end of their names.

Operator overloading is achieved by defining specific methods in your class. These methods are pre-defined in Python and are triggered when their corresponding operator is used. For instance, __add__ is for the + operator, and __lt__ is for the < operator.

For example, to overload the addition operator (+), you define the __add__ method. This method should return the result of the addition. Here's a simple example.

Output. (4, 6)

In this code, Point objects can be added using the + operator, and the __str__ method provides a readable string representation.

Similarly, you can overload other operators like subtraction (-) with __sub__ , multiplication (*) with __mul__ , and so on. Each operator has a corresponding magic method in Python.

It's essential to ensure that these methods return a new instance of the class or a suitable return value and not modify the existing instances unless that's the intended behaviour (like += does with __iadd__ ).

Overloading Comparison Operators In Python

Overloading comparison operators in Python is accomplished by defining specific methods in a class that correspond to these operators. This allows objects of the class to be compared using operators like ==, !=, <, >, <=, and >=, in a meaningful way.

Comparison operators are associated with special methods: __eq__ for ==, __ne__ for !=, __lt__ for <, __gt__ for >, __le__ for <=, and __ge__ for >=. By defining these methods, you can control how instances of your class are compared.

For instance, consider a class Rectangle where you want to compare rectangles based on their area.

Output. False True True

In this example, __eq__ is used for equality comparison based on area, and __lt__ for the 'less than' comparison. The area() method computes the area, which is the basis for comparison.

By overloading comparison operators, you enable intuitive comparisons for your custom objects, making your code more readable and elegant. These methods must return Boolean values (True or False), as they are used in conditional statements and logical expressions.

Overloading Equality And Less Than Operators

Overloading equality and less-than operators in Python is done by defining the __eq__ and __lt__ methods in a class. These methods enable objects of the class to use == for equality checks and < for less-than comparisons.

The __eq__ method is used to define a custom equality check. It should return True if the objects are considered equal and False otherwise. The __lt__ method is used to determine the logic for the less-than comparison, returning True if the first object is less than the second, and False otherwise.

Consider a class Book where books are compared based on the number of pages.

In this example, book1 and book3 are considered equal (==) because they have the same number of pages. book1 is less than (<) book2 as it has fewer pages.

By overloading these operators, Python allows you to define meaningful ways to compare objects based on their attributes, leading to more intuitive and readable code. It's important to ensure these methods are defined properly to avoid unexpected behaviour during comparisons.

Python Magic Methods Or Special Functions For Operator Overloading

Python magic methods, also known as special functions, are key to operator overloading in Python. They allow developers to define custom behaviors for operators when applied to objects of a custom class.

  • __add__(self, other) : Implements addition (+). Called when self + other is executed.
  • __sub__(self, other) : Implements subtraction (-). Invoked for self - other.
  • __mul__(self, other) : Defines multiplication (*). Used in self * other.
  • __truediv__(self, other) : For true division (/). Executed when self / other occurs.
  • __floordiv__(self, other) : Implements floor division (//). Called in self // other.
  • __mod__(self, other) : Defines modulo operation (%). Used for self % other.
  • __pow__(self, other) : For exponentiation (**). Invoked via self ** other.
  • __eq__(self, other) : Implements equality comparison (==). Called for self == other.
  • __ne__(self, other) : Defines not equal comparison (!=). Used in self != other.
  • __lt__(self, other) : Implements less than (<). Invoked for self < other.
  • __le__(self, other) : For less than or equal to (<=). Called in self <= other.
  • __gt__(self, other) : Defines greater than (>). Used when self > other is executed.
  • __ge__(self, other) : For greater than or equal to (>=). Invoked via self >= other.
  • __str__(self) : Customizes string representation. Called by str(self).
  • __repr__(self) : Defines official string representation. Used by repr(self).

These magic methods are the foundation of operator overloading in Python, enabling objects of custom classes to interact with Python operators seamlessly. By implementing these methods, developers can create objects that behave like built-in types, enhancing both the functionality and readability of the code.

Operator Overloading On Boolean Values

Operator overloading on boolean values in Python involves customizing the behaviour of logical operators for user-defined classes. This is primarily achieved through special methods that Python calls when evaluating an object in a boolean context or using logical operators.

The key methods for this purpose are:

  • __bool__(self) : Determines the truth value of an instance. Python calls this method when it needs to convert an instance to a boolean, for instance, when used in an if statement or with logical operators like and, or, not. It should return either True or False.
  • __len__(self) : This method is called if __bool__ is not defined. If __len__ returns zero, the object is considered False. Otherwise, it's considered True.

Here's an example using a custom class MyData.

In this example, MyData objects are considered True or False based on whether they contain data. The __bool__ method converts the object to a boolean by checking the truth value of its data attribute.

By overloading boolean operators, you can provide intuitive truthiness for your custom objects, making your code clearer and more Pythonic. This is especially useful when your class represents a collection or a concept where emptiness or the presence of content naturally translates to a boolean value.

Best Practices And Limitations

  • Consistency with Python’s built-in types: Your overloaded operators should mimic the behaviour of built-in types. For example, + should not alter the objects in place but should return a new object.
  • Returning NotImplemented: If your method is asked to handle a type it doesn't know about, it should return NotImplemented, not raise a TypeError.
  • Avoid overusing: While operator overloading can make your code more intuitive, overusing it or using it in non-obvious ways can lead to code that is hard to understand and maintain.

Operator overloading is a powerful feature in Python that, when used correctly, can lead to elegant and intuitive code. It allows your custom objects to behave like native Python objects, which can be particularly useful in mathematical or scientific computing. However, it’s important to use this feature judiciously to maintain the readability and maintainability of your code.

Operator overloading in Python showcases the language's flexibility and how it adheres to the principle of "everything is an object." By understanding and utilizing this feature, you can write more Pythonic and expressive code.

Work with top startups & companies. Get paid on time.

Try a top quality developer for 7 days. pay only if satisfied..

// Find jobs by category

You've got the vision, we help you create the best squad. Pick from our highly skilled lineup of the best independent engineers in the world.

  • Ruby on Rails
  • Elasticsearch
  • Google Cloud
  • React Native
  • Contact Details
  • 2093, Philadelphia Pike, DE 19703, Claymont
  • [email protected]
  • Explore jobs
  • We are Hiring!
  • Write for us
  • 2093, Philadelphia Pike DE 19703, Claymont

Copyright @ 2024 Flexiple Inc

CodersLegacy

Operator Overloading in Python

Operator Overloading is a handy feature in Python that allows us to “overload” or “over-ride” an operator with our own custom code. Operators such as + , - , * , / may not work in certain situations, such as when adding together two objects from custom classes you may have created.

In order to resolve this, we “overload” these operators to ensure it correctly adds the objects in a way that we find acceptable.

Regular Data Types

You must have already used various operators with the regular data types like int and string, like the example below.

These Data types have defined behavior for these various operations. The Custom Classes that we make however, do not have defined behavior (by default). We need to code in the behavior for each operator into the Classes that we make, in order for it work correctly.

In the below example, we will demonstrate what happens if you try to use the + operator on two objects of Class Data.

The above code produces the following error:

This error was thrown since there is no support for the addition between two Data objects.

Operator Overloading

The operators that we use so often, +, *, -, / and others have special methods associated with them that we need to write. The + operator for instance, has the __add__() function which gets called when the + operator is used. You can envision the function call as object1.__add__(object2) .

The following snipped overloads the __add__() function allowing for the addition of two data objects.

The + operator now works, because there is an appropriate __add__() method, which doesn’t try adding the objects, rather it adds the variables inside the object. You can add more than just one variable too. If your object has several, you can add them all together in the overloaded method.

Also note, that the reason we return a Data object from __add__() was because we were assigning it to a Data object. Otherwise d3 would have ended up as an int , not a Data object.

To output the new value in d3 , we can always do print(d3.value) , but what if we just overloaded the print operator itself? That way we could just do print(d3) , and we could print out the value(s) we want to display.

In order to overload print() , we need to overload the __str__() method in our Data class.

The __str__() must return a string, hence we have to convert self.value to string before returning. In the case of any other data type, an error will be thrown.

In this manner, you can overload almost any operator in Python. We have a complete list of overloadable operators in the tables below.

List of Overloadable Operators in Python

Besides the below operators, there are a few other functions and built-in methods that you can overload, such as __len__() .

Assignment based operators: (Note that the assignment operator itself, = , is not overloadable.

This marks the end of the Python Operator Overloading Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.

guest

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

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

logo

Book a Free Lesson

flag

Operator Overloading in Python

Written by Rahul Lath

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? Explore Wiingy’s Online Pytho n Tut oring . Learn from Top Coders and Software Developers .

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.

overloading assignment operator in python

Reviewed by

Share article on

tutor Pic

For enquiries call:

+1-469-442-0620

banner-in1

  • Programming

What Is Operator Overloading in Python?

Home Blog Programming What Is Operator Overloading in Python?

Play icon

Programmers can straightaway use pre-defined operators like  +, =, *, >, <,  etc. on built-in data types to write programs. However, these operators fail to work in user-defined data types. Therefore,  Python  comes up with  operator loading  capability, allowing programmers to redefine operators when working on class objects.   To learn more about  Self in Python , you can visit our website. Let us learn more about operator overloading in python, binary arithmetic operators, relational operators, and more. 

Operators Overloadin g  

Operator overloading allows programmers to extend the meaning of pre-defined operators. Simply put, it provides an expanded definition of  what is  pre-defined, making it easier for programmers to work seamlessly with both basic data types and user-defined data types.  

Operators Overloading

For instance, operator  ‘+’  will add two numbers, either by adding two ranges  or  combining two lists. You can do the same by overloading the  ‘+’  operator with the int and str class. Users may have observed that the identical built-in operator or function exhibits a particular  behaviour  for components of any specific Python class named operator overloading.  

Overloaded Operators  

Considering two items depicting a specific class,  where  you have to insert two objects using the binary  ‘+’  operator. Perhaps it will show an error  the  compiler   does  not understand  how to add. So, we describe an operator mechanism named overloading of the operator. Python includes a magic feature to conduct operator overloading  which is  immediately activated once paired with this same specific operator.  

  • For instance, when you are using the  ‘+’  operator, the  __add__  magical form can automatically describe the  ‘+’  operator operation.  
  • With built-in sets, the Python operator functions well. But for different forms, operators behave accordingly. For example, in two numbers, the  ‘+’  operator can apply addition, combine two lists, or merge multiple strings.  
  • Program to add without overloading the  ‘+’  operator.

Output:    

Oop s ! The program is not working and perhaps displays a  TypeError . Why? Because we have not yet expanded the code functionalities, and it is operating in built-in groups only. So, how can we enable these operators to run in our device class circles?  

Here the “magic techniques” enter the equatio n . In Python, magic methods include unique procedures that begin and finish with  __ init _ _ ( ).  The  __str_ _( )  technique is also another magic method  explicitly returning the spring representation of objects.  

Program to overload the + operator

Output :  

Let us look at one more example to understand overloading better:  

Program to subtract two complex numbers without overloading the - operator  

Program to overload the  ‘ - ‘  operator  on a complex object  

Stream extraction and insertion  

Many programming languages like C, C++, and Java have a standard library, allowing programmers to extract strings, numbers, and objects from text input stream with no hassle. Unfortunately, there is no availability for such a library for Python programmers. Python has a stream interface  –  classes that inherit from  io.IOBase  that provides facilities for line-oriented input. Perhaps if the user-inputs are arbitrary, the  re-module  must be the prime consideration.  

Increment and Decrement  

You may be familiar with  i ncrement and  d ecrement  o perators show n  by  +   +  and  -    -  separately if you were acquainted with C, Java,  or  PHP.  But i n Python, there seem to be no operators for incre ment or  decrement.  

I t may sound weird, but we code  +   =  or  x = x+ 2  in Python if we are to increase variable value by 2, and we are applying  -   =  or do  x = x – 2  to decrease it by 2.  

Possible conceptual explanations why Python  has  no increase and decrement operators  could be  becaus e  the same outcome  is  obtained through  +   =  or  -   =  seamlessly.  

Python code to illustrate Increment Operator        

Python code to illustrate  de crement operator  , assignment operators  .

The assignment operator, as the name suggests, assigns value to the operand. They are also known as shortcut operators, as they have been used to allocate variable values. The operator allows assigning the value of the operand on the right side of the operator. For instance, a = 4 is a simple attribution operator that attributes the value 4, right to the left variable a.  

Python Operators Overloading

Note:   Do not confuse in-place or shortcut operators. In Python, we have  = =  rational operators, which may look similar to including assignment operator.    

Note  the difference:  

With the use of the assignment operator, the variable gets assigned with a value, 4.  

In a relational operator, the variable checks the condition and displays the output in the Boolean value. If the expression condition gets satisfied, the code output  i s  True , else  F alse .  

Binary Arithmetic Operators  

Arithmetic operators like addi tion,  subtraction, multiplication, floor division, exponent (or power), and modulus are there by default in all the programming languages. In Python, all these arithmetic operators are binary, showing they are running on two controllers. Simply put, they run on two operators.  

Programmers apply these operators on numbers as well as on variables to perform corresponding operations.   The regular primary concern level is given to binary arithmetic operations. Notice that certain non-numeric forms of these operations often occur. Besides the power user, just two components are available, one for multiple operators and one category for additive operators . 

Let’s understand  binary arithmetic operators  with the help of an example. Assigning a = 50, and b = 100, we get the following outputs.  

Relational Operators  

Relational operators in Python are also o ften called comparison operators. These should measure and test the relationship between the operands on both sides. A Boolean value occurs in the comparison performance. These operators are being used to discover the association between two operands in the program. They are useful for the comparison of the values. It responds either  T rue   or  F alse , depending on the  conditi on.    

Let us understand  relational operators  with the help of an example. Assigning a = 50, and b = 100, we get the following output s .  

Array  

An array is a set of similar forms of components . Simply put, i t stores many data of the same type collectively. They may be helpful if there is a need for exploitation for such data types. The sorting of items stored in the array can be, however, extensively restricted by the users.    

To create an array, we need to import an array module.  

Here is a code where we have created an array of type  int . Notice the letter  i  is the type code.  

Here is a code where we have created an array of type  float . Notice the letter  d   is the type code.  

Bitwise operators  

Bitwise operators are operators in Python running at the binary level. That means   these operators  appear at the binary numbers or sections of an integer specifically. Much of this seems terrifying, but it is easy for bit operations. Compared with other operating systems, they are relatively fast since these procedures can be performed straight away  by the processor.   

Rather than words, bitwise operators are merely  labelled  with odd signs, making them look less wordy than you could see in Python.  Bitwise operators include:  

  • Bitwise  AND( &)  
  • Bitwise  OR( |)  
  • Bitwise  XOR( ^)  
  • Bitwise  NOT( ~)  
  • Shift  Left( <<)  
  • Shift  Right( >>)  

Overloaded Operators Restrictions  

When overloading operators, programmers are free to overload any arithmetic operators except the  =  operator. The thumb rule says:  Never try to overload  the  =   =  operator, because it becomes strenuous, and almost impossible to verify the test, whether the two objects are the same. Say  you  have an object x, which is from  a  custom class or is an integer , and you  want to see if x is the number 500.  I f you set  x = 500 , then later test  if  x is 500, you will get  False  because of the way Python caches numbers.   

Boolean negation operator  

When there is a need to reverse the  meaning of an  operand, we use the Boolean negation operator  using the keyword  not . This operator works by merely inverting the value of its an operand. If the expression you have to write is  True , placing the keyword  ‘ not ’  before it will return  False , and vice versa.

Let’s understand with the help of an example.  

N.B: In the defined list named classroom, we had four students attending the class. When we checked whether  “Bella”  is present in the list or not, we  got the  output as  Absent   because she i s present . Simply amazing how using  the  not  keyword  can reverse the entire meaning of the expression.  

Function Overloading in Python    

One of the perks of using Python is to overload functions, besides overloading operators. Python allows to overload functions like  long( ) ,  float( ) ,  abs( ) , and  hex( ) . We may alter the importance of a Python operator inside the category by overloading the operator. Programmers can use these functions to convert a value of a user-defined type (object) to a value of another type.  

Program to  overload  hex( ) ,   oct( ) , and  float( )  functions.  

Coders can run without overloading operators as well. With operator and functional overloading, it is easy to write efficient codes in basis and built-on data types. Perhaps  you will see  the real capabilities of operator overloadong in scientific computing while computong the representation of mathematical objects with no hassle. Otherwise, it would make the computation complex, time-consuming,  and  demanding.  

Profile

Abhresh Sugandhi

Abhresh is specialized as a corporate trainer, He has a decade of experience in technical training blended with virtual webinars and instructor-led session created courses, tutorials, and articles for organizations. He is also the founder of Nikasio.com, which offers multiple services in technical training, project consulting, content development, etc.

Avail your free 1:1 mentorship session.

Something went wrong

Upcoming Programming Batches & Dates

Course advisor icon

IMAGES

  1. Operator Overloading in Python (Polymorphism)

    overloading assignment operator in python

  2. Python: What is Operator Overloading in Python

    overloading assignment operator in python

  3. Python Operator Overloading

    overloading assignment operator in python

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

    overloading assignment operator in python

  5. Python OOP Tutorials

    overloading assignment operator in python

  6. Operator Overloading In Python with Easy Examples

    overloading assignment operator in python

VIDEO

  1. Assignment Operator

  2. OPERATOR OVERLOADING AND IN PYTHON

  3. Operator Overloading In Python #assignment #cybersecurity #svce

  4. Assignment & Relational Operator

  5. 50 Operator Overloading in Python

  6. C# Program to overload +,*,== on Complex Numbers

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. 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.

  4. Operator and Function Overloading in Custom Python Classes

    This is called operator overloading or function overloading respectively. This article will help you understand this mechanism, so that you can do the same in your own Python classes and make your objects more Pythonic. You'll learn the following: The API that handles operators and built-ins in Python.

  5. 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.

  6. 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 ...

  7. 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.

  8. Beyond the Basics: Mastering Advanced Operator Overloading Techniques

    Augmented assignment operators are used to assign and perform an operation at the same time. Here are some augmented assignment operators and their corresponding magic methods: ... Operator overloading in Python is a powerful mechanism that allows developers to redefine the behavior of standard operators for custom classes. By implementing ...

  9. 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.

  10. PDF CHAPTER 13 Operator Overloading: Doing It Right

    • The default handling of augmented assignment operators, like +=, and how to over‐ load them Operator Overloading 101 Operator overloading has a bad name in some circles. It is a language feature that can be (and has been) abused, resulting in programmer confusion, bugs, and unexpected performance bottlenecks.

  11. 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.

  12. 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.

  13. 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)

  14. 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 ...

  15. Operator Overloading In Python

    Operator overloading is achieved by defining specific methods in your class. These methods are pre-defined in Python and are triggered when their corresponding operator is used. For instance, __add__ is for the + operator, and __lt__ is for the < operator. For example, to overload the addition operator (+), you define the __add__ method.

  16. Operator Overloading in Python

    Operator Overloading is a handy feature in Python that allows us to "overload" or "over-ride" an operator with our own custom code. Operators such as +, -, *, / may not work in certain situations, such as when adding together two objects from custom classes you may have created.. In order to resolve this, we "overload" these operators to ensure it correctly adds the objects in a ...

  17. 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?

  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. operators

    Augmented operators in Python have to return the final value to be assigned to the name they are called on, usually (and in your case) self. Like all Python methods, missing a return statement implies returning None. Also, Never ever ever raise Exception, which is impossible to catch sanely.

  20. What is operator overloading in Python?

    Note: Do not confuse in-place or shortcut operators. In Python, we have = = rational operators, which may look similar to including assignment operator.. Note the difference: . With the use of the assignment operator, the variable gets assigned with a value, 4. # Assignment Operator a = 4 . In a relational operator, the variable checks the condition and displays the output in the Boolean value.