Questions And Answers

More Tutorials

Python Operator Overloading & Dunder Methods

Operator overloading and Dunder Methods may be new concepts for some of you. However, we have already seen similar concepts in which different methods act differently on different occasions and places. Let us understand the Operator overloading first.

Operator Overloading In Python

Operator overloading means giving new meanings to an operator. In simple words, it means to assign new functionality to an operator beyond its normal functioning. We will go with the most common and easiest that we could find related to the concept, i.e., the + sign. For numbers, it is used for addition between them, but in the case of a string, it is used to join or combine two strings, working differently in two different scenarios. The operators are methods defined in respective classes. Defining methods for operators is known as operator overloading.

Python Dunder Methods Or Special Functions

Dunder methods in Python are special methods. In Python, we sometimes see method names with a double underscore (__), such as the __init__ method that every class has. These methods are called “dunder” methods. In Python, Dunder methods are used for operator overloading and customizing some other function’s behavior.

Python usually calls dunder methods under the hood. Suppose we want to join a string with a number using the + sign. Now joining between two different data types is not possible in Python, and the resultant in such a case will be an error. So for this purpose, we can use a function provided to us by Python, named as dunder function. We will write such code in it so that it may first convert the number to a string and then join them, or any other logic will be fine too until it does what we require. We can even return 85; regardless of what string or number is given to us, it is all up to us.

Methods starting with a double underscore ( __ ) and ending with a double underscore ( __ ) represent dunder methods.

__str__ and __repr__ functions

Both of these built-in methods are used to return a presentable description of any object rather than the default one. The difference in them is the way of writing them. The __str__ method is mainly written for the end-user, while __repr__ is written for a developer. It is overridden to return a printable string representation of any user-defined class. An interesting thing to note here is that the priority of __str__ is greater than __repr__. This means that if we pass an object into a print statement, it will return us the __str__ string even if __repr__ is also present there. In such cases, if we want to print __repr__, we have to call it exclusively with the object name in the print statement.

Difference between __str__ and __repr__ functions

1. If the implementation of __str__ is missing, then __repr__ function is used as a fallback. If the implementation of __repr__ is missing, then there will be no fallback.
2. If __repr__ function is returning the object's String representation, we can skip the implementation of __str__ function.
3. The priority of __str__ is higher than __repr__.


class Employee:
    no_of_leaves = 8

    def __init__(self, aname, asalary, arole): = aname
        self.salary = asalary
        self.role = arole

    def printdetails(self):
        return f"The Name is {}. Salary is {self.salary} and role is {self.role}"

    def change_leaves(cls, newleaves):
        cls.no_of_leaves = newleaves

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

    def __truediv__(self, other):
        return self.salary / other.salary

    def __repr__(self):
        return f"Employee('{}', {self.salary}, '{self.role}')"

    def __str__(self):
        return f"The Name is {}. Salary is {self.salary} and role is {self.role}"

emp1 =Employee("Harry", 345, "Programmer")
# emp2 =Employee("Rohan", 55, "Cleaner")


In this page (written and validated by ) you learned about Python Operator Overloading & Dunder Methods . What's Next? If you are interested in completing Python tutorial, your next topic will be learning about: Python Abstract Base Class and abstractmethod.

Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue:

Share On:

Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using, you agree to have read and accepted our terms of use, cookies and privacy policy.