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:

OperatorSpecial Methods
+__add__(self, other)
__sub__(self, other)
* __mul__(self, other)
/ __truediv__(self, other)
// __floordiv__(self, other)
% __mod__(self, other)
** __pow__(self, other)
>> __rshift__(self, other)
<< __lshift__(self, other)
& __and__(self, other)
| __or__(self, other)
^ __xor__(self, other)

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:

OperatorSpecial Method
+=__iadd__(self, other)
-=__isub__(self, other)
*= __imul__(self, other)
/= __itruediv__(self, other)
//= __ifloordiv__(self, other)
%= __imod__(self, other)
**= __ipow__(self, other)
>>= __irshift__(self, other)
<<= __ilshift__(self, other)
&= __iand__(self, other)
|= __ior__(self, other)
^= __ixor__(self, other)

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.

Operator and Function Overloading in Python

Operator and Function Overloading in Custom Python Classes

Table of Contents

The Python Data Model

The internals of operations like len() and [], giving a length to your objects using len(), making your objects work with abs(), printing your objects prettily using str(), representing your objects using repr(), making your objects truthy or falsey using bool(), making your objects capable of being added using +, shortcuts: the += operator, indexing and slicing your objects using [], reverse operators: making your classes mathematically correct, a complete example, recap and resources.

If you’ve used the + or * operator on a str object in Python, you must have noticed its different behavior when compared to int or float objects:

You might have wondered how the same built-in operator or function shows different behavior for objects of different 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
  • The “secret” behind len() and other built-ins
  • How to make your classes capable of using operators
  • How to make your classes compatible with Python’s built-in functions

Free Bonus: Click here to get access to a free Python OOP Cheat Sheet that points you to the best tutorials, videos, and books to learn more about Object-Oriented Programming with Python.

As a bonus, you’ll also see an example class, objects of which will be compatible with many of these operators and functions. Let’s get started!

Say you have a class representing an online order having a cart (a list ) and a customer (a str or instance of another class which represents a customer).

Note: If you need a refresher on OOP in Python, check out this tutorial on Real Python: Object-Oriented Programming (OOP) in Python 3

In such a case, it is quite natural to want to obtain the length of the cart list. Someone new to Python might decide to implement a method called get_cart_len() in their class to do this. But you can configure the built-in len() in such a way that it returns the length of the cart list when given our object.

In another case, we might want to append something to the cart. Again, someone new to Python would think of implementing a method called append_to_cart() that takes an item and appends it to the cart list. But you can configure the + operator in such a way that it appends a new item to the cart.

Python does all this using special methods . These special methods have a naming convention, where the name starts with two underscores , followed by an identifier and ends with another pair of underscores.

Essentially, each built-in function or operator has a special method corresponding to it. For example, there’s __len__(), corresponding to len() , and __add__() , corresponding to the + operator.

By default, most of the built-ins and operators will not work with objects of your classes. You must add the corresponding special methods in your class definition to make your object compatible with built-ins and operators.

When you do this, the behavior of the function or operator associated with it changes according to that defined in the method.

This is exactly what the Data Model (Section 3 of the Python documentation) helps you accomplish. It lists all the special methods available and provides you with the means of overloading built-in functions and operators so that you can use them on your own objects.

Let’s see what this means.

Fun fact: Due to the naming convention used for these methods, they are also called dunder methods which is a shorthand for d ouble under score methods . Sometimes they’re also referred to as special methods or magic methods . We prefer dunder methods though!

Every class in Python defines its own behavior for built-in functions and methods. When you pass an instance of some class to a built-in function or use an operator on the instance, it is actually equivalent to calling a special method with relevant arguments.

If there is a built-in function, func() , and the corresponding special method for the function is __func__() , Python interprets a call to the function as obj.__func__() , where obj is the object. In the case of operators, if you have an operator opr and the corresponding special method for it is __opr__() , Python interprets something like obj1 <opr> obj2 as obj1.__opr__(obj2) .

So, when you’re calling len() on an object, Python handles the call as obj.__len__() . When you use the [] operator on an iterable to obtain the value at an index, Python handles it as itr.__getitem__(index) , where itr is the iterable object and index is the index you want to obtain.

Therefore, when you define these special methods in your own class, you override the behavior of the function or operator associated with them because, behind the scenes, Python is calling your method. Let’s get a better understanding of this:

As you can see, when you use the function or its corresponding special method, you get the same result. In fact, when you obtain the list of attributes and methods of a str object using dir() , you’ll see these special methods in the list in addition to the usual methods available on str objects:

If the behavior of a built-in function or operator is not defined in the class by the special method, then you will get a TypeError .

So, how can you use special methods in your classes?

Overloading Built-in Functions

Many of the special methods defined in the Data Model can be used to change the behavior of functions such as len , abs , hash , divmod , and so on. To do this, you only need to define the corresponding special method in your class. Let’s look at a few examples:

To change the behavior of len() , you need to define the __len__() special method in your class. Whenever you pass an object of your class to len() , your custom definition of __len__() will be used to obtain the result. Let’s implement len() for the order class we talked about in the beginning:

As you can see, you can now use len() to directly obtain the length of the cart. Moreover, it makes more intuitive sense to say “length of order” rather than calling something like order.get_cart_len() . Your call is both Pythonic and more intuitive. When you don’t have the __len__() method defined but still call len() on your object, you get a TypeError :

But, when overloading len() , you should keep in mind that Python requires the function to return an integer. If your method were to return anything other than an integer, you would get a TypeError . This, most probably, is to keep it consistent with the fact that len() is generally used to obtain the length of a sequence, which can only be an integer:

You can dictate the behavior of the abs() built-in for instances of your class by defining the __abs__() special method in the class. There are no restrictions on the return value of abs() , and you get a TypeError when the special method is absent in your class definition.

In a class representing a vector in a two-dimensional space, abs() can be used to get the length of the vector. Let’s see it in action:

It makes more intuitive sense to say “absolute value of vector” rather than calling something like vector.get_mag() .

The str() built-in is used to cast an instance of a class to a str object, or more appropriately, to obtain a user-friendly string representation of the object which can be read by a normal user rather than the programmer. You can define the string format your object should be displayed in when passed to str() by defining the __str__() method in your class. Moreover, __str__() is the method that is used by Python when you call print() on your object.

Let’s implement this in the Vector class to format Vector objects as xi+yj . A negative y-component will be handled using the format mini-language :

It is necessary that __str__() returns a str object, and we get a TypeError if the return type is non-string.

The repr() built-in is used to obtain the parsable string representation of an object. If an object is parsable, that means that Python should be able to recreate the object from the representation when repr is used in conjunction with functions like eval() . To define the behavior of repr() , you can use the __repr__() special method.

This is also the method Python uses to display the object in a REPL session. If the __repr__() method is not defined, you will get something like <__main__.Vector object at 0x...> trying to look at the object in the REPL session. Let’s see it in action in the Vector class:

Note: In cases where the __str__() method is not defined, Python uses the __repr__() method to print the object, as well as to represent the object when str() is called on it. If both the methods are missing, it defaults to <__main__.Vector ...> . But __repr__() is the only method that is used to display the object in an interactive session. Absence of it in the class yields <__main__.Vector ...> .

Also, while this distinction between __str__() and __repr__() is the recommended behavior, many of the popular libraries ignore this distinction and use the two methods interchangeably.

Here’s a recommended article on __repr__() and __str__() by our very own Dan Bader: Python String Conversion 101: Why Every Class Needs a “repr” .

The bool() built-in can be used to obtain the truth value of an object. To define its behavior, you can use the __bool__() ( __nonzero__() in Python 2.x) special method.

The behavior defined here will determine the truth value of an instance in all contexts that require obtaining a truth value such as in if statements.

As an example, for the Order class that was defined above, an instance can be considered to be truthy if the length of the cart list is non-zero. This can be used to check whether an order should be processed or not:

Note: When the __bool__() special method is not implemented in a class, the value returned by __len__() is used as the truth value, where a non-zero value indicates True and a zero value indicates False . In case both the methods are not implemented, all instances of the class are considered to be True .

There are many more special methods that overload built-in functions. You can find them in the documentation . Having discussed some of them, let’s move to operators.

Overloading Built-in Operators

Changing the behavior of operators is just as simple as changing the behavior of functions. You define their corresponding special methods in your class, and the operators work according to the behavior defined in these methods.

These are different from the above special methods in the sense that they need to accept another argument in the definition other than self , generally referred to by the name other . Let’s look at a few examples.

The special method corresponding to the + operator is the __add__() method. Adding a custom definition of __add__() changes the behavior of the operator. It is recommended that __add__() returns a new instance of the class instead of modifying the calling instance itself. You’ll see this behavior quite commonly in Python:

You can see above that using the + operator on a str object actually returns a new str instance, keeping the value of the calling instance ( a ) unmodified. To change it, we need to explicitly assign the new instance to a .

Let’s implement the ability to append new items to our cart in the Order class using the operator. We’ll follow the recommended practice and make the operator return a new Order instance that has our required changes instead of making the changes directly to our instance:

Similarly, you have the __sub__() , __mul__() , and other special methods which define the behavior of - , * , and so on. These methods should return a new instance of the class as well.

The += operator stands as a shortcut to the expression obj1 = obj1 + obj2 . The special method corresponding to it is __iadd__() . The __iadd__() method should make changes directly to the self argument and return the result, which may or may not be self . This behavior is quite different from __add__() since the latter creates a new object and returns that, as you saw above.

Roughly, any += use on two objects is equivalent to this:

Here, result is the value returned by __iadd__() . The second assignment is taken care of automatically by Python, meaning that you do not need to explicitly assign obj1 to the result as in the case of obj1 = obj1 + obj2 .

Let’s make this possible for the Order class so that new items can be appended to the cart using += :

As can be seen, any change is made directly to self and it is then returned. What happens when you return some random value, like a string or an integer?

Even though the relevant item was appended to the cart, the value of order changed to what was returned by __iadd__() . Python implicitly handled the assignment for you. This can lead to surprising behavior if you forget to return something in your implementation:

Since all Python functions (or methods) return None implicitly, order is reassigned to None and the REPL session doesn’t show any output when order is inspected. Looking at the type of order , you see that it is now NoneType . Therefore, always make sure that you’re returning something in your implementation of __iadd__() and that it is the result of the operation and not anything else.

Similar to __iadd__() , you have __isub__() , __imul__() , __idiv__() and other special methods which define the behavior of -= , *= , /= , and others alike.

Note: When __iadd__() or its friends are missing from your class definition but you still use their operators on your objects, Python uses __add__() and its friends to get the result of the operation and assigns that to the calling instance. Generally speaking, it is safe to not implement __iadd__() and its friends in your classes as long as __add__() and its friends work properly (return something which is the result of the operation).

The Python documentation has a good explanation of these methods. Also, take a look at this example which shows the caveats involved with += and the others when working with immutable types.

The [] operator is called the indexing operator and is used in various contexts in Python such as getting the value at an index in sequences, getting the value associated with a key in dictionaries, or obtaining a part of a sequence through slicing. You can change its behavior using the __getitem__() special method.

Let’s configure our Order class so that we can directly use the object and obtain an item from the cart:

You’ll notice that above, the name of the argument to __getitem__() is not index but key . This is because the argument can be of mainly three forms: an integer value , in which case it is either an index or a dictionary key, a string value , in which case it is a dictionary key, and a slice object , in which case it will slice the sequence used by the class. While there are other possibilities, these are the ones most commonly encountered.

Since our internal data structure is a list, we can use the [] operator to slice the list, as in this case, the key argument will be a slice object. This is one of the biggest advantages of having a __getitem__() definition in your class. As long as you’re using data structures that support slicing (lists, tuples, strings, and so on), you can configure your objects to directly slice the structure:

Note: There is a similar __setitem__() special method that is used to define the behavior of obj[x] = y . This method takes two arguments in addition to self , generally called key and value , and can be used to change the value at key to value .

While defining the __add__() , __sub__() , __mul__() , and similar special methods allows you to use the operators when your class instance is the left-hand side operand, the operator will not work if the class instance is the right-hand side operand:

If your class represents a mathematical entity like a vector, a coordinate, or a complex number , applying the operators should work in both the cases since it is a valid mathematical operation.

Moreover, if the operators work only when the instance is the left operand, we are violating the fundamental principle of commutativity in many cases. Therefore, to help you make your classes mathematically correct, Python provides you with reverse special methods such as __radd__() , __rsub__() , __rmul__() , and so on.

These handle calls such as x + obj , x - obj , and x * obj , where x is not an instance of the concerned class. Just like __add__() and the others, these reverse special methods should return a new instance of class with the changes of the operation rather than modifying the calling instance itself.

Let’s configure __radd__() in the Order class in such a way that it will append something at the front of the cart. This can be used in cases where the cart is organized in terms of the priority of the orders:

To drive all these points home, it’s better to look at an example class which implements these operators together.

Let’s reinvent the wheel and implement our own class to represent complex numbers, CustomComplex . Objects of our class will support a variety of built-in functions and operators, making them behave very similar to the built-in complex numbers class:

The constructor handles only one kind of call, CustomComplex(a, b) . It takes positional arguments, representing the real and imaginary parts of the complex number.

Let’s define two methods inside the class, conjugate() and argz() , which will give us the complex conjugate and the argument of a complex number respectively:

Note: __class__ is not a special method but a class attribute which is present by default. It has a reference to the class. By using it here, we are obtaining that and then calling the constructor in the usual manner. In other words, this is equivalent to CustomComplex(real, imag) . This is done here to avoid refactoring the code if the name of the class changes someday.

Next, we configure abs() to return the modulus of a complex number:

We will follow the recommended distinction between __repr__() and __str__() and use the first for the parsable string representation and the second for a “pretty” representation.

The __repr__() method will simply return CustomComplex(a, b) in a string so that we can call eval() to recreate the object, while the __str__() method will return the complex number in brackets, as (a+bj) :

Mathematically, it is possible to add any two complex numbers or add a real number to a complex number. Let’s configure the + operator in such a way that it works for both cases.

The method will check the type of the right-hand side operator. In case it is an int or a float , it will increment only the real part (since any real number, a , is equivalent to a+0j ), while in the case of another complex number, it will change both the parts:

Similarly, we define the behavior for - and * :

Since both addition and multiplication are commutative, we can define their reverse operators by calling __add__() and __mul__() in __radd__() and __rmul__() respectively. On the other hand, the behavior of __rsub__() needs to be defined since subtraction is not commutative:

Note: You might have noticed that we didn’t add a construct to handle a CustomComplex instance here. This is because, in such a case, both the operands are instances of our class, and __rsub__() won’t be responsible for handling the operation. Instead, __sub__() will be called. This is a subtle but important detail.

Now, we take care of the two operators, == and != . The special methods used for them are __eq__() and __ne__() , respectively. Two complex numbers are said to be equal if their corresponding real and imaginary parts are both equal. They are said to be unequal when either one of these are unequal:

Note: The Floating-Point Guide is an article that talks about comparing floats and floating-point precision. It highlights the caveats involved in comparing floats directly, which is something we’re doing here.

It is also possible to raise a complex number to any power using a simple formula . We configure the behavior for both the built-in pow() and the ** operator using the __pow__() special method:

Note: Take a close look at the definition of the method. We are calling abs() to obtain the modulus of the complex number. So, once you’ve defined the special method for a particular function or operator in your class, it can be used in other methods of the same class.

Let’s create two instances of this class, one having a positive imaginary part and one having a negative imaginary part:

String representations:

Recreating the object using eval() with repr() :

Addition, subtraction, and multiplication:

Equality and inequality checks:

Finally, raising a complex number to some power:

As you can see, objects of our custom class behave and look like those of a built-in class and are very Pythonic. The full example code for this class is embedded below.

Solution: "A Complete Example" Show/Hide

In this tutorial, you learned about the Python Data Model and how the Data Model can be used to build Pythonic classes. You learned about changing the behavior of built-in functions such as len() , abs() , str() , bool() , and so on. You also learned about changing the behavior of built-in operators like + , - , * , ** , and so forth.

After reading this, you can confidently create classes that make use of the best idiomatic features of Python and make your objects Pythonic!

For more information on the Data Model, and function and operator overloading, take a look at these resources:

  • Section 3.3, Special Method Names of the Data Model section in the Python documentation
  • Fluent Python by Luciano Ramalho
  • Python Tricks: The Book

🐍 Python Tricks 💌

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge

About Malay Agarwal

Malay Agarwal

A tech geek with a philosophical mind and a hand that can wield a pen.

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Aldren Santos

Master Real-World Python Skills With Unlimited Access to Real Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

What Do You Think?

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal . Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session . Happy Pythoning!

Keep Learning

Related Topics: intermediate python

Keep reading Real Python by creating a free account or signing in:

Already have an account? Sign-In

Almost there! Complete this form and click the button below to gain instant access:

Python OOP Cheat Sheet

Object-Oriented Programming in Python: The 7 Best Resources (A Free PDF Cheat Sheet)

🔒 No spam. We take your privacy seriously.

python assignment operator overload

Learn Python practically and Get Certified .

Popular Tutorials

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

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

Python Fundamentals

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

Python Operators

Python Flow Control

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

Python Data types

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

Python Files

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

Python Object & Class

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

Python Operator Overloading

Python advanced topics.

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

Python Date and Time

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

Additional Topic

Precedence and Associativity of Operators in Python

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

Python Tutorials

Python dir()

  • Python object()

Python Lists Vs Tuples

In Python, we can change the way operators work for user-defined types.

For example, the + operator will perform arithmetic addition on two numbers, merge two lists , or concatenate two strings .

This feature in Python that allows the same operator to have different meaning according to the context is called operator overloading .

  • Python Special Functions

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

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

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

Here are some of the special functions available in Python,

Function Description
initialize the attributes of the object
returns a string representation of the object
returns the length of the object
adds two objects
call objects of the class like a normal function

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.

Operator Expression Internally
Addition
Subtraction
Multiplication
Power
Division
Floor Division
Remainder (modulo)
Bitwise Left Shift
Bitwise Right Shift
Bitwise AND
Bitwise OR
Bitwise XOR
Bitwise NOT
  • 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.

Operator Expression Internally
Less than
Less than or equal to
Equal to
Not equal to
Greater than
Greater than or equal to
  • 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

  • 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

Facebook Page

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

OperatorMagic Method
+=__iadd__(self, other)
-=__isub__(self, other)
*=__imul__(self, other)
/=__idiv__(self, other)
//=__ifloordiv__(self, other)
%=__imod__(self, other)
**=__ipow__(self, other)
&=__iand__(self, other)
|=__ior__(self, other)
^=__ixor__(self, other)
>>=__irshift__(self, other)
<<=__ilshift__(self, other)

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

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

OPERATORMAGIC METHOD
__add__(self, other)
__sub__(self, other)
__mul__(self, other)
__truediv__(self, other)
__floordiv__(self, other)
__mod__(self, other)
__pow__(self, other)

Magic Methods for Comparison Operators in Python

OPERATORMAGIC METHOD
__lt__(self, other)
__gt__(self, other)
__le__(self, other)
__ge__(self, other)
__eq__(self, other)
__ne__(self, other)

Magic Methods for Assignment Operators in Python

OPERATORMAGIC METHOD
__isub__(self, other)
__iadd__(self, other)
__imul__(self, other)
__idiv__(self, other)
__ifloordiv__(self, other)
__imod__(self, other)
__ipow__(self, other)

Magic Methods for Unary Operators

OPERATORMAGIC METHOD
__neg__(self, other)
__pos__(self, other)
__invert__(self, other)

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

Python Geeks

Learn Python Programming from Scratch

  • Learn Python

Python Operator Overloading

FREE Online Courses: Your Passport to Excellence - Start Now

Modifying the behavior of an operator by redefining the method an operator invokes is called Operator Overloading. It allows operators to have extended behavior beyond their pre-defined behavior. Let us first discuss operators, operands, and their behavior before diving into the operator overloading.

Operators and Operands in Python

Special symbols in Python that we use to perform various operations on objects are called Operators. The objects on which operations are performed are called Operands. We say objects because everything is an object in Python.

Example of Operators in Python

In the above code example, + is the operator that performs the addition operation on operands num1 and num2.

Behavior of Operators in Python

The behavior of operators, in Python, is different for different operands. The same operator performs different actions depending on the operands used. Let us understand this using the plus operator.

In the above code example, operands are two int objects and the plus operator returns their sum.

Operators on Strings in Python

In the above code example, operands are two string objects and the plus operator returns their concatenated string.

Operators on Lists in Python

In the above code example, operands are two list objects and the plus operator joined the two lists and returned the joined list.

From the above three code examples, we can see that the plus operator performs three different operations depending on the operands. It performs the sum operation if the operands are numbers, concatenation if the operands are strings, and join operation if the operands are lists. Similarly, operators in Python have different behaviors for different operands.

Magic Methods in Python

Python contains a special type of method called Magic Methods or Special Methods or Dunder Methods. These methods have two underscores before and after their name. Usually, we never directly call those functions. Python invokes them internally.

For example, whenever we create an object, Python invokes __init__ method to instantiate the object and whenever we use an operator, Python internally calls the corresponding magic method.

We can see in the above code example, we never directly called the __init__ method. Python invoked it as soon as we defined an object.

Limitations of Operators in Python

Operators have certain limitations depending on their operands. For example, the + operator can not perform addition if the operands are objects other than numbers, strings, tuples, and lists. It runs a TypeError instead of a sum.

In the above code example, when we try to add two Fruit objects, Python returns a TypeError.

We can remove these limitations through operator overloading and make the + operator return something instead of an error.

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.

We can redefine this method in our object’s class to create a custom operation for the + operator. This is also called Operator Ad-hoc Polymorphism.

In the above code example, we used the plus operator for two Fruit objects. Since we redefined the __add__ method, + returned a string instead of an error.

Similarly, operator overloading can be done for all types of operators except logical and identity operators in Python.

Types of Operators in Python

There are seven types of operators in Python. Among those, we can overload five types of operators.

Types of operators in Python we can overload

Arithmetic operators Comparison operators Assignment operators
Bitwise operators Membership operators

Types of Python operators we can not overload

Logical operators Identity operators

Arithmetic Operators in Python

Arithmetic operators are two types: Unary operators and Binary Operators.

1. Unary Operators in Python

+ __pos__
__neg__
~ __invert__

Example: Negative Operator (-)

In the above code example, by overloading the ‘-’ operator, we made it always print a string and return a positive number instead of a negative number.

2. Binary Operators in Python

+ __add__
__sub__
* __mul__
/ __truediv__
// __floordiv__
% __mod__
** __pow__

Example: Modulus Operator (%)

In the above code example, we overloaded the ‘%’ operator to return the quotient of the division instead of the remainder.

Comparison Operators in Python

> __gt__
< __lt__
== __eq__
>= __ge__
<= __le__
!= __ne__

Example: Equal-to Operator (==)

In the above code example, Instead of checking whether two strings are the same or not, we redefined the equal-to operator to check whether two strings are of equal length or not.

Assignment Operators in Python

+=  __iadd__
-= __isub__
*= __imul__
/= __idiv__
//= __ifloordiv__
%= __imod__
**= __ipow__
>>= __irshift__
<<= __ilshift__
&= __iand__
^= __ixor__
|= __ior__

Example: Addition Assignment Operator (+=)

In the above code example, we overloaded the ‘+=’ operator to always add 5 instead of the given number. 

 Bitwise Operators in Python

>> __rshift__
<< __lshift__
& __and__
^ __xor__
| __or__
~ __invert__

Example: And Operator (&)

In the above code example, we overloaded the ‘&’ operator to return a string.

Membership Operators in Python

in __contains__
not in

These operators are a bit different. Membership operators ‘in’ and ‘not in’ both invoke the same method __contains__. 

Any value in the return statement is automatically converted into a boolean value, that is, either True or False. 

Example: in and not in Operators

In the above code example, we overloaded the __contains__ method. So the ‘in’ operator always returns False and the ‘not in’ operator always returns True.

Python Interview Questions on Operator Overloading

Q1. Overload the minus (-) operator to print the string “Subtracting”.

Ans 1. Complete code is as follows:

Q2. Inverse the role of the greater-than (>) operator by making it perform the less-than operation.

Ans 2. Code is as follows:

Q3. Overload the + operator to easily add 2D coordinates.

Ans 3. Code is as follows:

Q4. Change the role of the multiply operator to the dividing operator.

Ans 4. Code is as follows:

Q5. What is the output of the following code?

Ans 5. The output of the given code is

{1: ‘one’, 2: ‘two’, 3: ‘three’}

Quiz on Python Operator Overloading

Quiz summary.

0 of 10 Questions completed

Information

You have already completed the quiz before. Hence you can not start it again.

Quiz is loading…

You must sign in or sign up to start the quiz.

You must first complete the following:

Quiz complete. Results are being recorded.

0 of 10 Questions answered correctly

Time has elapsed

You have reached 0 of 0 point(s), ( 0 )

Earned Point(s): 0 of 0 , ( 0 ) 0 Essay(s) Pending (Possible Point(s): 0 )

  • Not categorized 0%
  • Review / Skip

1 . Question

What type of methods are invoked by the operators?

  • Instance methods
  • Class methods
  • Static methods
  • Magic methods

2 . Question

 In Python, +, -, and, / are called ____.

3 . Question

For what operands does the addition operator perform concatenation operation?

4 . Question

What method is invoked by the addition operator?

  • __addition__

5 . Question

What operator invokes the __irshift__ method?

6 . Question

 What is the output of the below code?

>>> class Multiply:

>>>    def __init__(self, x):

>>>        self.x = x

>>>    def __mul__(self, other):

>>>        return f”{self.x} X {other.x} = {self.x * other.x}”

>>> a = Multiply(5)

>>> b = Multiply(10)

>>> print(a * b)

  • 5 X 10 = 50
  • a X b = a * b
  • Both A and B

7 . Question

What is the output of the below code?

>>> class Class1:

>>>    def __init__(self, n):

>>>        self.n = n

>>>    def __add__(self, other):

>>>        return self.n – other.n

>>> a = Class1(4)

>>> b = Class1(1)

>>> print(a + b)

  • SyntaxError

8 . Question

>>> class Car:

>>>    def __init__(self, speed):

>>>        self.speed = speed

>>>    def __gt__(self, other):

>>>        if self.speed > other.speed:

>>>            return “Car1 is faster than Car2”

>>>        else:

>>>            return “Car2 is faster than Car1”

>>> car1 = Car(130)

>>> car2 = Car(250)

>>> print(car1 > car2)

  • Car1 is faster than Car2
  • Car2 is faster than Car1

9 . Question

>>> class Words:

>>>    def __init__(self, str):

>>>        self.str = str

>>>    def __truediv__(self, other):

>>>        return len(self.str) / len(other.str)

>>> word1 = Words(“Hello Worlds”)

>>> word2 = Words(“Python”)

>>> print(word1 / word2)

10 . Question

Choose the correct missing line to complete the code.

>>> class Hello:

>>>    def __iadd__(self, other):

>>>        return “Adding”

>>> a = Hello()

>>> # Missing Line

>>> print(a)

  • a = Hello() + Hello()
  • Hello() += a
  • a =+ Hello()
  • a += Hello()

In this article, we learned about operators and how to overload them. Overloading operators come in handy in several situations. When we are working on geometry projects, overloading the addition operator to add coordinates is one of the many examples where we can use Python Overloading.

Furthermore, if you have any queries, please feel free to share them with us in the comment section.

We work very hard to provide you quality material Could you take 15 seconds and share your happy experience on Google | Facebook

Tags: Behavior of Operators in Python Magic methods in Python Operators on Lists in Python Python Operator Overloading

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

Username or Email Address

Remember Me

python geeks logo

Operator Overloading In Python

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

Nadim Jendoubi

Nadim Jendoubi

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

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

Operator Overloading 101

What is it.

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

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

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

Benefits of operator overloading

We can notice different pros such as:

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

Overloading Unary Operators

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

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

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

Overloading Arithmetic Operators

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

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

Addition Operator and Mixed Type Addition

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

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

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

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

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

Multiplication Operator and Mixed Type Multiplication

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

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

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

Overview of Arithmetic Operators

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

Infix operator method names,  image taken from Fluent Python book

Overloading Comparison Operators

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

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

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

Overloading Augmented Assignment Operators

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

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

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

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

Further Reading

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

Common Index Anomalies and Database Performance Tuning

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

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

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

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

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

Iterators VS Generator VS Classic Coroutines in Python

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

Find Study Materials for

  • Explanations
  • Business Studies
  • Combined Science
  • Computer Science
  • Engineering
  • English literature
  • Environmental Science
  • Human Geography
  • Macroeconomics
  • Microeconomics
  • Social Studies
  • Browse all subjects
  • Textbook Solutions
  • Read our Magazine

Create Study Materials

  • Flashcards Create and find the best flashcards.
  • Notes Create notes faster than ever before.
  • Study Sets Everything you need for your studies in one place.
  • Study Plans Stop procrastinating with our smart planner features.
  • Python Assignment Operator

Dive into the world of Python programming and explore the essential role that Python Assignment Operators play in simplifying and optimising your code. This comprehensive guide will help you understand the basics of Python Assignment Operators, and learn about the different types available, followed by detailed explanations and examples to solidify your grasp. Furthermore, you will discover the concept of overloading in the context of Python Assignment Operators, and find out how it can be applied in custom classes for enhanced functionality. Lastly, you will gain invaluable insights into Python Assignment Operator precedence, along with useful tips to manage precedence effectively and streamline your coding experience. Embark on this fascinating journey to expand your Python knowledge and enrich your programming skills.

Python Assignment Operator

Create learning materials about Python Assignment Operator with our free learning app!

  • Instand access to millions of learning materials
  • Flashcards, notes, mock-exams and more
  • Everything you need to ace your exams
  • Algorithms in Computer Science
  • Computer Network
  • Computer Organisation and Architecture
  • Computer Programming
  • 2d Array in C
  • AND Operator in C
  • Access Modifiers
  • Actor Model
  • Algorithm in C
  • Array as function argument in c
  • Assignment Operator in C
  • Automatically Creating Arrays in Python
  • Bitwise Operators in C
  • C Arithmetic Operations
  • C Array of Structures
  • C Functions
  • C Math Functions
  • C Memory Address
  • C Plus Plus
  • C Program to Find Roots of Quadratic Equation
  • C Programming Language
  • Change Data Type in Python
  • Classes in Python
  • Comments in C
  • Common Errors in C Programming
  • Compound Statement in C
  • Concurrency Vs Parallelism
  • Concurrent Programming
  • Conditional Statement
  • Critical Section
  • Data Types in Programming
  • Declarative Programming
  • Decorator Pattern
  • Distributed Programming
  • Do While Loop in C
  • Dynamic allocation of array in c
  • Encapsulation programming
  • Event Driven Programming
  • Exception Handling
  • Executable File
  • Factory Pattern
  • For Loop in C
  • Formatted Output in C
  • Functions in Python
  • How to return multiple values from a function in C
  • Identity Operator in Python
  • Imperative programming
  • Increment and Decrement Operators in C
  • Inheritance in Oops
  • Insertion Sort Python
  • Instantiation
  • Integrated Development Environments
  • Integration in C
  • Interpreter Informatics
  • Java Abstraction
  • Java Annotations
  • Java Arithmetic Operators
  • Java Arraylist
  • Java Arrays
  • Java Assignment Operators
  • Java Bitwise Operators
  • Java Classes And Objects
  • Java Collections Framework
  • Java Constructors
  • Java Data Types
  • Java Do While Loop
  • Java Enhanced For Loop
  • Java Expection Handling
  • Java File Class
  • Java File Handling
  • Java Finally
  • Java For Loop
  • Java Function
  • Java Generics
  • Java IO Package
  • Java If Else Statements
  • Java If Statements
  • Java Inheritance
  • Java Interfaces
  • Java List Interface
  • Java Logical Operators
  • Java Map Interface
  • Java Method Overloading
  • Java Method Overriding
  • Java Multidimensional Arrays
  • Java Multiple Catch Blocks
  • Java Nested If
  • Java Nested Try
  • Java Non Primitive Data Types
  • Java Operators
  • Java Polymorphism
  • Java Primitive Data Types
  • Java Queue Interface
  • Java Recursion
  • Java Reflection
  • Java Relational Operators
  • Java Set Interface
  • Java Single Dimensional Arrays
  • Java Statements
  • Java Static Keywords
  • Java Switch Statement
  • Java Syntax
  • Java This Keyword
  • Java Try Catch
  • Java Type Casting
  • Java Virtual Machine
  • Java While Loop
  • Javascript Anonymous Functions
  • Javascript Arithmetic Operators
  • Javascript Array Methods
  • Javascript Array Sort
  • Javascript Arrays
  • Javascript Arrow Functions
  • Javascript Assignment Operators
  • Javascript Async
  • Javascript Asynchronous Programming
  • Javascript Await
  • Javascript Bitwise Operators
  • Javascript Callback
  • Javascript Callback Functions
  • Javascript Changing Elements
  • Javascript Classes
  • Javascript Closures
  • Javascript Comparison Operators
  • Javascript DOM Events
  • Javascript DOM Manipulation
  • Javascript Data Types
  • Javascript Do While Loop
  • Javascript Document Object
  • Javascript Event Loop
  • Javascript For In Loop
  • Javascript For Loop
  • Javascript For Of Loop
  • Javascript Function
  • Javascript Function Expressions
  • Javascript Hoisting
  • Javascript If Else Statement
  • Javascript If Statement
  • Javascript Immediately Invoked Function Expressions
  • Javascript Inheritance
  • Javascript Interating Arrays
  • Javascript Logical Operators
  • Javascript Loops
  • Javascript Multidimensional Arrays
  • Javascript Object Creation
  • Javascript Object Prototypes
  • Javascript Objects
  • Javascript Operators
  • Javascript Primitive Data Types
  • Javascript Promises
  • Javascript Reference Data Types
  • Javascript Scopes
  • Javascript Selecting Elements
  • Javascript Spread And Rest
  • Javascript Statements
  • Javascript Strict Mode
  • Javascript Switch Statement
  • Javascript Syntax
  • Javascript Ternary Operator
  • Javascript This Keyword
  • Javascript Type Conversion
  • Javascript While Loop
  • Linear Equations in C
  • Log Plot Python
  • Logical Error
  • Logical Operators in C
  • Loop in programming
  • Matrix Operations in C
  • Membership Operator in Python
  • Model View Controller
  • Nested Loops in C
  • Nested if in C
  • Numerical Methods in C
  • OR Operator in C
  • Object orientated programming
  • Observer Pattern
  • One Dimensional Arrays in C
  • Oops concepts
  • Operators in Python
  • Parameter Passing
  • Pascal Programming Language
  • Plot in Python
  • Plotting In Python
  • Pointer Array C
  • Pointers and Arrays
  • Pointers in C
  • Polymorphism programming
  • Procedural Programming
  • Programming Control Structures
  • Programming Language PHP
  • Programming Languages
  • Programming Paradigms
  • Programming Tools
  • Python Arithmetic Operators
  • Python Array Operations
  • Python Arrays
  • Python Bar Chart
  • Python Bitwise Operators
  • Python Bubble Sort
  • Python Comparison Operators
  • Python Data Types
  • Python Indexing
  • Python Infinite Loop
  • Python Loops
  • Python Multi Input
  • Python Range Function
  • Python Sequence
  • Python Sorting
  • Python Subplots
  • Python while else
  • Quicksort Python
  • R Programming Language
  • Race Condition
  • Ruby programming language
  • Runtime System
  • Scatter Chart Python
  • Secant Method
  • Shift Operator C
  • Single Structures In C
  • Singleton Pattern
  • Software Design Patterns
  • Statements in C
  • Storage Classes in C
  • String Formatting C
  • String in C
  • Strings in Python
  • Structures in C
  • Swift programming language
  • Syntax Errors
  • Threading In Computer Science
  • Variable Informatics
  • Variable Program
  • Variables in C
  • Version Control Systems
  • While Loop in C
  • Write Functions in C
  • exclusive or operation
  • for Loop in Python
  • if else in C
  • if else in Python
  • scanf Function with Buffered Input
  • switch Statement in C
  • while Loop in Python
  • Computer Systems
  • Data Representation in Computer Science
  • Data Structures
  • Functional Programming
  • Issues in Computer Science
  • Problem Solving Techniques
  • Theory of Computation

The Basics of Python Assignment Operators

Assignment operators in Python are used to assign values to variables. They allow programmers to perform different types of operations and store the results in variables.

Different types of Python Assignment Operators

=Assigns a value to a variable
+=Addition assignment
-=Subtraction assignment
*=Multiplication assignment
/=Division assignment
%=Modulus assignment
//=Floor division assignment
**=Exponentiation assignment
&=Bitwise AND assignment
|=Bitwise OR assignment
^=Bitwise XOR assignment
>>=Bitwise right shift assignment
<<=Bitwise left shift assignment

How Python Assignment Operators work

Addition assignment operator example: x = 10 # x is assigned the value 10 x += 5 # x is updated to x + 5, which is 15 print(x) # The output will be 15

Python assignment operators not only save time by making code shorter but also offer the advantage of improved performance. Compound assignment operators can lead to faster execution as the interpreted language like Python can optimize such operations more effectively than separate operations.

Python Assignment Operator List and Examples

As we delve deeper into the world of Python assignment operators, we can see that each of these operators serves a distinct purpose and offers unique advantages. To gain a comprehensive understanding of their functionality, let's explore some common Python assignment operators in great detail with the help of practical examples.

+=, -=, *=, and **= Assignment Operators in Python

  • += (Addition assignment): This operator is used to add the value on the right to the variable on the left and then update the value of the variable.
  • -= (Subtraction assignment): This operator is used to subtract the right side value from the left side variable and then update the value of the variable.
  • *= (Multiplication assignment): This operator is used to multiply the value on the right with the variable on the left and then update the value of the variable.
  • **= (Exponentiation assignment): This operator is used to raise the variable on the left to the power of the value on the right and then update the value of the variable.

x = 10 # x is assigned the value 10 x += 5 # x is updated to x + 5, which is 15 x -= 3 # x is updated to x - 3, which is 12 x *= 2 # x is updated to x * 2, which is 24 x **= 2 # x is updated to x ** 2, which is 576 print(x) # The output will be 576

/=, //=, %=, and &= Assignment Operators in Python

  • /= (Division assignment): This operator is used to divide the variable on the left by the value on the right and then update the value of the variable.
  • //= (Floor division assignment): This operator performs floor division on the left side variable by the right side value and then updates the value of the variable.
  • %= (Modulus assignment): This operator calculates the modulus of the left side variable divided by the right side value and then updates the value of the variable.
  • &= (Bitwise AND assignment): This operator performs a bitwise AND operation between the left side variable and the right side value, and then updates the value of the variable.

x = 50 # x is assigned the value 50 x /= 2 # x is updated to x / 2, which is 25 x //= 3 # x is updated to x // 3, which is 8 x %= 5 # x is updated to x % 5, which is 3 x &= 2 # x is updated to x & 2, which is 2 print(x) # The output will be 2

Overloading Python Assignment Operators

What is python assignment operator overloading, using python assignment operator overloading in custom classes.

  • __add__(): Corresponds to the '+=' operator
  • __sub__(): Corresponds to the '-=' operator
  • __mul__(): Corresponds to the '*=' operator
  • __truediv__(): Corresponds to the '/=' operator
  • __floordiv__(): Corresponds to the '//=' operator
  • __mod__(): Corresponds to the '%=' operator
  • __pow__(): Corresponds to the '**=' operator
  • __and__(): Corresponds to the '&=' operator
  • __or__(): Corresponds to the '|=' operator
  • __xor__(): Corresponds to the '^=' operator
  • __lshift__(): Corresponds to the '<<=' operator
  • __rshift__(): Corresponds to the '>>=' operator

Advantages of Python Assignment Operator Overloading

  • Improved readability: By overloading assignment operators, you can make your code more self-explanatory and easier to understand since the operators are more intuitive than function calls.
  • Enhanced expressiveness: Operator overloading enables custom classes to provide a natural syntax that closely resembles the native data types, allowing programmers to write more concise and efficient code.
  • Increased consistency: When operators are consistently represented across user-defined and built-in classes, the language semantics remain uniform, resulting in improved consistency.
  • Greater abstraction: Overloading assignment operators allows you to hide the implementation details from the users, providing them with a straightforward and consistent interface for interacting with custom objects.

Python Assignment Operator Precedence

Understanding operator precedence in python, precedence rules for python assignment operators.

  • Assignment operators (=, +=, -=, *=, etc.) are evaluated from right to left.
  • Assignment operators have a lower precedence compared to all arithmetic, relational, and logical operators.
  • When multiple assignment operators are present in an expression, Python evaluates the rightmost assignment operator first and proceeds from right to left.

To illustrate these precedence rules, consider the following example: ```python x = 10 + 5 * 2 ``` In this example, the multiplication (*) operator takes precedence over the addition (+) and assignment (=) operators. Therefore, the expression will be evaluated as follows: `x = 10 + (5 * 2)`. The final value of x will be 20.

Tips for Managing Python Assignment Operator Precedence

  • Always use parentheses to group operations explicitly and avoid ambiguities. Using parentheses not only ensures that the expression is evaluated in the correct order but also improves the readability of your code.
  • When evaluating complex expressions, break them down into smaller, simpler expressions and assign intermediate results to temporary variables. This approach not only makes your code more readable but also minimizes the chance of encountering precedence issues.
  • If you are uncertain about the precedence levels of the operators involved in an expression, consult the Python documentation for clarification. Familiarizing yourself with the precedence rules will significantly enhance your ability to write accurate and reliable code.
  • Always test your code thoroughly to ensure that the operator precedence does not introduce any unintended outcomes. Adequate testing will help you identify and correct potential errors and ambiguities caused by operator precedence.

Python Assignment Operator - Key takeaways

Python Assignment Operator - used to assign values to variables and perform operations while updating variable values.

Python assignment operator overload - using 'magic methods' to extend functionality of assignment operators for custom classes.

Python assignment operator list - Basic (=) and compound (+=, -=, *=, etc.) assignment operators available in Python for different types of operations.

What is the assignment operator in python? - '=' is the basic assignment operator used for assigning values to variables.

Python assignment operator precedence - Set of rules governing the order in which assignment operators are executed in an expression, assignment operators have the lowest precedence level.

Flashcards in Python Assignment Operator 31

What is the basic assignment operator in Python?

The basic assignment operator in Python is the equals sign (=), which assigns values to variables.

What is the purpose of assignment operators in Python?

Assignment operators in Python are used to assign values to variables and perform various operations such as addition, subtraction, multiplication, and division on stored values.

Which assignment operator is used to add a value to an existing variable in Python?

The addition assignment operator (+=) is used to add a value to an existing variable in Python.

What does the floor division assignment operator (//=) do in Python?

The floor division assignment operator (//=) in Python divides the value of a variable by another value and assigns the quotient's largest integer less than or equal to the result.

How do you use the multiplication assignment operator (*=) in Python?

To use the multiplication assignment operator (*=) in Python, write 'variable_name *= value', which multiplies the variable's value by the given value and assigns the result to the variable.

What is operator precedence in Python?

Operator precedence in Python is a set of rules that define the order in which different operators are executed in an expression, affecting the final output.

Python Assignment Operator

Learn with 31 Python Assignment Operator flashcards in the free Vaia app

We have 14,000 flashcards about Dynamic Landscapes.

Already have an account? Log in

Frequently Asked Questions about Python Assignment Operator

Test your knowledge with multiple choice flashcards.

Python Assignment Operator

Join the Vaia App and learn efficiently with millions of flashcards and more!

Keep learning, you are doing great.

Discover learning materials with the free Vaia app

1

Vaia is a globally recognized educational technology company, offering a holistic learning platform designed for students of all ages and educational levels. Our platform provides learning support for a wide range of subjects, including STEM, Social Sciences, and Languages and also helps students to successfully master various tests and exams worldwide, such as GCSE, A Level, SAT, ACT, Abitur, and more. We offer an extensive library of learning materials, including interactive flashcards, comprehensive textbook solutions, and detailed explanations. The cutting-edge technology and tools we provide help students create their own learning materials. StudySmarter’s content is not only expert-verified but also regularly updated to ensure accuracy and relevance.

Python Assignment Operator

Vaia Editorial Team

Team Python Assignment Operator Teachers

  • 12 minutes reading time
  • Checked by Vaia Editorial Team

Study anywhere. Anytime.Across all devices.

Create a free account to save this explanation..

Save explanations to your personalised space and access them anytime, anywhere!

By signing up, you agree to the Terms and Conditions and the Privacy Policy of Vaia.

Sign up to highlight and take notes. It’s 100% free.

Join over 22 million students in learning with our Vaia App

The first learning app that truly has everything you need to ace your exams in one place

  • Flashcards & Quizzes
  • AI Study Assistant
  • Study Planner
  • Smart Note-Taking

Join over 22 million students in learning with our Vaia App

Privacy Overview

Basics of Python

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

Complex Datatypes

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

OOPS Concept

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

Error Handling

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

Multithreading

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

Miscellaneous

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

Python Logging

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

Python With MySQL

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

Operator overloading in Python

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

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

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

Can + Operator Add anything?

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

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

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

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

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

Special Functions in Python

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

Mathematical Operator

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

Name Symbol Special Function
Addition
Subtraction
Division
Floor Division
Modulus(or Remainder)
Power

Assignment Operator

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

Name Symbol Special Function
Increment
Decrement
Product
Division
Modulus
Power

Relational Operator

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

Name Symbol Special Function
Less than
Greater than
Equal to
Not equal
Less than or equal to
Greater than or equal to

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

Overloading + operator

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

sum = 7 + 7i

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

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

Overloading < operator

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

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

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

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

  • ← Prev
  • Next →

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.  

Python Arithmetic OperatorsOperationExampleOutput
+Addition – adds the operandsprint(a+b)150
-Subtraction – subtracts operand on the right from the operands on the left of the operatorprint(a-b)-50
*Multiplication – Multiplies the operandsprint(a*b)5000
/Division – Divides operand on the left side of the operator with the operand on the right, and returns the quotient as output.print(b/a)2.0
%Modulus – Divides operand on the left side of the operator with the operand on the right, and returns the remainder as output.print(b%a)0
//Floor Division – Divides operand on the left side of the operator with the operand on the right, and returns the quotient without any decimal point.print(b//a)2
**Exponent – It raises the operand on the left side of the operator with the operand on the right performing exponential calculation.print(a**b)50

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 .  

Python Relational OperatorsDescriptionExampleOutput
==Returns True if the values at both operands on the left and the value of operator and operand are equal.print(a == b)False
!=Returns True if the values at both operands on the left and the value of operator and operand are unequal.print(a != b)True
>Returns True if the values at operand on the left are greater than the value of operator are equal.print(a >= b)False
<Returns True if the values at operand on the left are lesser than the value of operator are equal.print(a <= b)True
>=Returns True if the values at operand on the left are greater than or equal to the value of operator are equal.print(a >= b)False
<=Returns True if the values at operand on the left are lesser than or equal to the value of operator are equalprint(a <= b)True

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

NameDateFeeKnow more

Course advisor icon

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 –

Expression During Execution
obj1 + obj2obj1.__add__(obj2)
obj1 – obj2obj1.__sub__(obj2)
obj1 * obj2 obj1.__mul__(obj2)
obj1 / obj2 obj1.__truediv__(obj2)
obj1 // obj2 obj1.__floordiv__(obj2)
obj1 % obj2 obj1.__mod__(obj2)
obj1 ** obj2 obj1.__pow__(obj2)
obj1 & obj2 obj1.__and__(obj2)
obj1 ^ obj2 obj1.__xor__(obj2)
obj1 | obj2 obj1.__or__(obj2)

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

Expression
During Execution
obj1 < obj2obj1.__lt__(obj2)
obj1 <= obj2 obj1.__le__(obj2)
obj1 == obj2 obj1.__eq__(obj2)
obj1 != obj2 obj1.__ne__(obj2)
obj1 > obj2 obj1.__gt__(obj2)
obj1 >= obj2 obj1.__ge__(obj2)

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

Expression During Execution
obj1 += obj2obj1.__iadd__(obj2)
obj1 -= obj2obj1.__isub__(obj2)
obj1 *= obj2 obj1.__imul__(obj2)
obj1 /= obj2 obj1.__itruediv__(obj2)
obj1 //= obj2 obj1.__ifloordiv__(obj2)
obj1 %= obj2 obj1.__imod__(obj2)
obj1 **= obj2 obj1.__ipow__(obj2)
obj1 &= obj2 obj1.__iand__(obj2)
obj1 ^= obj2 obj1.__ixor__(obj2)
obj1 |= obj2 obj1.__ior__(obj2)

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:

python assignment operator overload

Recommended Articles

Leave a reply cancel reply.

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 $2400 scholarship for School and College Students

What do you want to learn?

Operator Overloading in Python

Written by Rahul Lath

Updated on: 07 Dec 2023

Python Tutorials

tutor Pic

What is Operator Overloading in Python?

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

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

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

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

How to Overload Operators in Python?

Magic Methods and Their Usage

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

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

Example Code Snippets

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

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

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

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

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

Overloading Binary + Operator in Python

A. Explanation of Binary + Operator Overloading-

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

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

B. Example Code Snippets

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

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

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

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

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

How Does Operator Overloading Actually Work?

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

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

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

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

Overloading Comparison Operators in Python

Explanation of Comparison Operator Overloading

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

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

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

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

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

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

Advantages of Operator Overloading in Python

Explanation of Benefits of Operator

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

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

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

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

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

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

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

Overloading Built-in Functions

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

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

  • Giving Length to Your Objects Using len()

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

Here’s an example:

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

  • Making Your Objects Work With abs()

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

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

  • Printing Your Objects Prettily Using str()

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

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

  • Representing Your Objects Using repr()

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

Examples of Operator Overloading in Python

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

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

  • Overloading “<” Operator:

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

  • Overloading “+” Operator:

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

  • Overloading Comparison Operators:

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

  • Overloading Equality Operator:

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

B. Example code snippets:

2. Overloading “+” Operator:

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

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

Magic Methods for Operator Overloading in Python

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

Here are some common magic methods for operator overloading:

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

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

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

  • Assignment Operators :

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

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

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

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

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

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

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

What is operator overloading in Python?

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

What is operator overloading with example?

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

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

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

What is operator overloading with syntax?

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

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

The syntax for defining an operator overload is:

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

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

python assignment operator overload

Reviewed by

Share article on

tutor Pic

Table of Contents

Introduction , assignment operator, addition assignment operator, subtraction assignment operator, multiplication assignment operator, division assignment operator, modulus assignment operator, floor division assignment operator, exponentiation assignment operator, bitwise and assignment operator, bitwise or assignment operator, bitwise xor assignment operator , bitwise right shift assignment operator, bitwise left shift assignment operator, walrus operator, conclusion , python assignment operator: tips and tricks to learn.

Assignment Operators in Python

Assignment operators are vital in computer programming because they assign values to variables. Python stores and manipulates data with assignment operators like many other programming languages . First, let's review the fundamentals of Python assignment operators so you can understand the concept.

In Python, the following operators are often used for assignments:

Sign Type of Python Operators = Assignment Operator += Addition assignment -= Subtraction assignment *= Multiplication assignment /= Division assignment %= Modulus assignment //= Floor division assignment **= Exponentiation assignment &= Bitwise AND assignment |= Bitwise OR assignment ^= Bitwise XOR assignment >>= Bitwise right shift assignment <<= Bitwise left shift assignment := Walrus Operator

Python uses in-fix assignment operators to perform operations on variables or operands and assign values to the operand on the left side of the operator. It carries out calculations involving arithmetic, logical, and bitwise operations.

Python assignment operator provides a way to define assignment statements. This statement allows you to create, initialize, and update variables throughout your code, just like a software engineer. Variables are crucial in any code; assignment statements provide complete control over creating and modifying variables.

Understanding the Python assignment operator and how it is used in assignment statements can equip you with valuable tools to enhance the quality and reliability of your Python code.

In Python, the equals sign (=) is the primary assignment operator. It assigns the variable's value on the left side to the value on the right side of the operator.

Here's a sample to think about:

In this code snippet, the variable 'x' is given the value of 6. The assignment operator doesn't check for equality but assigns the value.

Become a Software Development Professional

  • 13 % CAGR Estimated Growth By 2026
  • 30 % Increase In Job Demand

Python Training

  • 24x7 learner assistance and support

Automation Testing Masters Program

  • Comprehensive blended learning program
  • 200 hours of Applied Learning

Here's what learners are saying regarding our programs:

Charlotte Martinez

Charlotte Martinez

This is a good course for beginners as well as experts with all the basic concepts explained clearly. It's a good starter to move to python programming for programmers as well as non- programmers

Daniel Altufaili

Daniel Altufaili

It infrastructure oprations , johnson electric.

Upon finishing the QA automation course, I received fresh assignments at my job owing to my heightened proficiency in IT, IoT, and ML. In addition to this, I earned a promotion and 20% salary increase. This course significantly expanded my expertise and motivated me to continuously enhance my skills through ongoing upskilling efforts.

The addition assignment operator (+=) adds the right-hand value to the left-hand variable.

The addition assignment operator syntax is variable += value.

The addition assignment operator increments a by 5. The console displays 14 as the result.

The subtraction assignment operator subtracts a value from a variable and stores it in the same variable.

The subtraction assignment operator syntax is variable-=-value.

Using the multiplication assignment operator (=), multiply the value on the right by the variable's existing value on the left.

The assignment operator for multiplication has the following syntax: variable *= value

In this situation, the multiplication assignment operator multiplies the value of a by 2. The output, 10, is shown on the console.

Using the division assignment operator (/=), divide the value of the left-hand variable by the value of the right-hand variable.

The assignment operator for division has the following syntax: variable /= value

Using the division assignment operator, divide a value by 3. The console displays 5.0.

The modulus assignment operator (% =) divides the left and right variable values by the modulus. The variable receives the remainder.

The modulus assignment operator syntax is variable %= value.

The modulus assignment operator divides a by 2. The console displays the following: 1.

Use "//" to divide and assign floors in one phrase. What "a//=b" means is "a=a//b". This operator cannot handle complicated numbers.

The floor division assignment operator syntax is variable == value.

The floor division assignment operator divides a by 2. The console displays 5.

The exponentiation assignment operator (=) elevates the left variable value to the right value's power.

Operator syntax for exponentiation assignment:

variable**=value

The exponentiation assignment operator raises a to 2. The console shows 9.

The bitwise AND assignment operator (&=) combines the left and right variable values using a bitwise AND operation. Results are assigned to variables.

The bitwise AND assignment operator syntax is variable &= value.

The bitwise AND assignment operator ANDes a with 2. The console displays 2 as the outcome.

The bitwise OR assignment operator (|=) bitwise ORs the left and right variable values.

The bitwise OR assignment operator syntax is variable == value.

A is ORed with 4 using the bitwise OR assignment operator. The console displays 6.

Use the bitwise XOR assignment operator (^=) to XOR the left and right values of a variable. Results are assigned to variables.

For bitwise XOR assignment, use the syntax: variable ^= value.

The bitwise XOR assignment operator XORs a with 4. The console displays 2 as the outcome.

The right shift assignment operator (>>=) shifts the variable's left value right by the number of places specified on the right.

The assignment operator for the bitwise right shift has the following syntax:

variable >>= value

The bitwise right shift assignment operator shifts 2 places to the right. The result is 1.

The variable value on the left moves left by the specified number of places on the right using the left shift assignment operator (<<=).

The bitwise left shift assignment operator syntax is variable <<= value.

When we execute a Bitwise right shift on 'a', we get 00011110, which is 30 in decimal.

Python gets new features with each update. Emily Morehouse added the walrus operator to Python 3.8's initial alpha. The most significant change in Python 3.8 is assignment expressions. The ":=" operator allows mid-expression variable assignment. This operator is called the walrus operator.

variable := expression

It was named for the operator symbol (:=), which resembled a sideways walrus' eyes and tusks.

Walrus operators simplify code authoring, which is its main benefit. Each user input was stored in a variable before being passed to the for loop to check its value or apply a condition. It is important to note that the walrus operator cannot be used alone.

With the walrus operator, you can simultaneously define a variable and return a value.

Above, we created two variables, myVar and value, with the phrase myVar = (value = 2346). The expression (value = 2346) defines the variable value using the walrus operator. It returns the value outside the parenthesis as if value = 2346 were a function. 

The variable myVar is initialized using the return value from the expression (value = 2346). 

The output shows that both variables have the same value.

Learn more about other Python operators by reading our detailed guide here .

Discover how Python assignment operators simplify and optimize programs. Python assignment operators are explained in length in this guide, along with examples, to help you understand them. Start this intriguing journey to improve your Python knowledge and programming skills with Simplilearn's Python training course .

1. What is the ":=" operator in Python?

Python's walrus operator ":" evaluates, assigns, and returns a value from a single sentence. Python 3.8 introduces it with this syntax (variable:=expression).

2. What does = mean in Python?

The most significant change in Python 3.8 is assignment expressions. The walrus operator allows mid-expression variable assignment.

3. What is def (:) Python?

The function definition in Python is (:). Functions are defined with def. A parameter or parameter(s) follows the function name. The function body begins with an indentation after the colon (:). The function body's return statement determines the value.

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees

Cohort Starts:

6 Months$ 8,000

Cohort Starts:

11 Months$ 1,499

Cohort Starts:

6 Months$ 1,449

Cohort Starts:

6 Months$ 1,449

Recommended Reads

Python Interview Guide

Filter in Python

Understanding Python If-Else Statement

Top Job Roles in the Field of Data Science

Yield in Python: An Ultimate Tutorial on Yield Keyword in Python

The Best Tips for Learning Python

Get Affiliated Certifications with Live Class programs

  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.
  • Trending Now
  • Foundational Courses
  • Data Science
  • Practice Problem
  • Machine Learning
  • System Design
  • DevOps Tutorial

Default Arguments in Python

In this video, we will explore the concept of default arguments in Python. Default arguments allow you to define functions with default values for parameters, making your functions more flexible and easier to use. This tutorial is perfect for students, professionals, or anyone interested in enhancing their Python programming skills by understanding and utilizing default arguments effectively.

Why Use Default Arguments?

Default arguments enable you to call functions with fewer arguments than they are defined to accept. This makes your code more concise and provides a way to handle optional parameters without needing to overload functions or use complex logic.

Key Concepts

1. Default Arguments:

  • Parameters that assume a default value if no argument is provided during the function call.

2. Function Definition:

  • Default values are specified in the function definition using the assignment operator (=).

3. Function Call:

  • When calling the function, if no argument is provided for a default parameter, the default value is used.

Steps to Use Default Arguments

Step 1: Define a Function with Default Arguments

  • Define a function with parameters, some of which have default values assigned.

Step 2: Call the Function

  • Call the function providing values for all parameters.
  • Call the function providing values for only some of the parameters, allowing the default values to be used for others.
  • Call the function without providing any arguments, using all default values.

Practical Example

Example: Function with Default Arguments

Define Function:

  • Create a function greet with two parameters: name and greeting, where greeting has a default value.

Call Function:

  • Call greet with both arguments, with only the name argument, and with no arguments to see how default values are applied.

Practical Applications

Optional Parameters:

  • Use default arguments to handle optional parameters, making your functions more versatile and easier to call with varying numbers of arguments.

Simplifying Function Calls:

  • Reduce the complexity of function calls by providing reasonable default values, especially for parameters that are often the same.

Flexible APIs:

  • Design more flexible APIs and interfaces, allowing users to override default behavior when necessary while maintaining simplicity for common cases.

Additional Resources

For more detailed information and a comprehensive guide on default arguments in Python, check out the full article on GeeksforGeeks: https://www.geeksforgeeks.org/default-arguments-in-python/ . This article provides in-depth explanations, examples, and further readings to help you master the use of default arguments in Python functions.

By the end of this video, you’ll have a solid understanding of default arguments in Python, enhancing your ability to write flexible and concise functions.

Read the full article for more details: https://www.geeksforgeeks.org/default-arguments-in-python/ .

Thank you for watching!

Video Thumbnail

  • Stack Overflow Public questions & answers
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Talent Build your employer brand
  • Advertising Reach developers & technologists worldwide
  • Labs The future of collective knowledge sharing
  • About the company

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

extended assignment statements in Python [closed]

How can I add extended operators(below). Generally speaking how can I implement such an operator (for example only one).

  • operator-overloading
  • overloading

JosephAndrew2's user avatar

  • 1 Stack Overflow is not intended to replace existing tutorials and documentation. The operators in question are called "augmented assignment" operators, so the first place you should look is to put something like python augmented assignment into a search engine. Even without knowing that, something like python operator overloading should give you some relevant results. –  Karl Knechtel Commented Apr 14, 2021 at 10:26

By implementing, for example, __iadd__ . See "Emulating numeric types" in the language reference.

Ture Pålsson's user avatar

Not the answer you're looking for? Browse other questions tagged python operator-overloading operators overloading or ask your own question .

  • Featured on Meta
  • Upcoming sign-up experiments related to tags
  • Policy: Generative AI (e.g., ChatGPT) is banned
  • The return of Staging Ground to Stack Overflow
  • The 2024 Developer Survey Is Live

Hot Network Questions

  • Is it grammatically correct to say 'I suspect this clause to be a bit sloppy English'?
  • Did the NES CPU save die area by omitting BCD?
  • Arrays. Find row with most 1's, in O(n)
  • My supervisor is promoting my work (that I think has flaws) everywhere - what to do?
  • Replacing grass against side of house
  • John, in his spaceship traveling at relativistic speed, is crossing the Milky Way in 500 years. How many supernovae explosions would he experience?
  • Does it matter to de-select faces before going back to Object Mode?
  • What camera could I mount or rig to my bike that can read/recognize license plates
  • How can you destroy a mage hand?
  • In general, How's a computer science subject taught in Best Universities of the World that are not MIT level?
  • Contour shading: how to shade only the positive contours?
  • Movie with a gate guarded by two statues
  • Why do some op amps' datasheet specify phase margin at open loop?
  • Can you perform harmonics on wine glasses?
  • Reviewers do not live up to own quality standards
  • How to re-use QGIS map layout for other projects /How to create a print layout template?
  • Are many figures in a paper considered bad practice?
  • Story featuring an alien with an exotic sensorium (sonar?) that helps solve a murder
  • What is the relevance and meaning if a sentence contains "Had not"?
  • Do rich parents pay less in child support if they didn't provide a rich lifestyle for their family pre-divorce?
  • Why can real number operations be applied to complex numbers?
  • Are there any well-known mathematicians who were marxists?
  • Will it break Counterspell if the trigger becomes "perceive" instead of "see"?
  • How to send transaction bundles?

python assignment operator overload

IMAGES

  1. Operator Overloading in Python (Polymorphism)

    python assignment operator overload

  2. Python: What is Operator Overloading in Python

    python assignment operator overload

  3. SOLUTION: Operator Overloading in python

    python assignment operator overload

  4. Python Tips Series: Operator Overloading

    python assignment operator overload

  5. Python Tutorial #48

    python assignment operator overload

  6. Python Operator Overloading

    python assignment operator overload

VIDEO

  1. Assignment

  2. Assignment Operator in Python Lec 7

  3. Dasar Python

  4. add and assignment operator overload #cpp #coding #cplusplus #oop #programmingtutorial #tajmirkhan

  5. python Assignment operator #shorts #python #assignment #operator #print #coding #programming

  6. python Assignment operator #shorts #python #assignment #operator #coding #programming

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

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

  4. How to Emulate Assignment Operator Overloading in Python?

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

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

  6. Operator and Function Overloading in Custom Python Classes

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

  7. Python 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. Python Assignment Operator Overloading

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

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

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

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

  12. operator overloading in python

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

  13. Python Assignment Operator: Overload, List, Precedence

    What is Python Assignment Operator Overloading? Operator overloading is a programming concept that allows the same operator to perform various functions based on the types of operands interacted within an operation. In Python, we can overload assignment operators using special methods called 'magic methods' or 'dunder methods' (double ...

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

  15. Python Operator Overloading

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

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

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

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

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

  20. Python Assignment Operator: A Comprehensive Guide 2024!

    Assignment Operator Overview Python uses in-fix assignment operators to perform operations on variables or operands and assign values to the operand on the left side of the operator. It carries out calculations involving arithmetic, logical, and bitwise operations. Python assignment operator provides a way to define assignment statements.

  21. Python overloading variable assignment

    Python overloading variable assignment. Ask Question Asked 9 years, 11 months ago. Modified 9 years, 11 months ago. Viewed 2k times ... Operator overloading in python with the object on the right hand side of the operator. 0. method overloading python. 51. Overload operator in Python. 0.

  22. Default arguments in Python

    Default values are specified in the function definition using the assignment operator (=). 3. Function Call: When calling the function, if no argument is provided for a default parameter, the default value is used. Steps to Use Default Arguments. Step 1: Define a Function with Default Arguments. Function Definition:

  23. operator overloading

    1. Stack Overflow is not intended to replace existing tutorials and documentation. The operators in question are called "augmented assignment" operators, so the first place you should look is to put something like python augmented assignment into a search engine. Even without knowing that, something like python operator overloading should give ...