How can we overload operators in Python?
Python > Operators in Python > Python Operators Introduction
277
Answer:
Operator overloading in Python is the process of defining special methods in a class that correspond to the different operators, allowing you to use those operators with objects of your class. These methods are also known as "magic methods" or "dunder methods" because their names are surrounded by double underscores (e.g., add for the + operator).
To overload an operator in Python, you need to define the corresponding magic method in your class. Here are some of the commonly used magic methods 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.__floordiv__(self, other)
: Overloads the // operator for floor division.__mod__(self, other)
: Overloads the % operator for modulus.__pow__(self, other[, modulo])
: Overloads the ** operator for exponentiation.__and__(self, other)
: Overloads the & operator for bitwise AND.__or__(self, other)
: Overloads the | operator for bitwise OR.__xor__(self, other)
: Overloads the ^ operator for bitwise XOR.__lt__(self, other)
: Overloads the < operator for less than.__le__(self, other)
: Overloads the <= operator for less than or equal to.__eq__(self, other)
: Overloads the == operator for equality.__ne__(self, other)
: Overloads the != operator for not equal to.__gt__(self, other)
: Overloads the > operator for greater than.__ge__(self, other)
: Overloads the >= operator for greater than or equal to.__neg__(self)
: Overloads the - operator for negation.__pos__(self)
: Overloads the + operator for positive values.__invert__(self)
: Overloads the ~ operator for bitwise inversion.
When you define a magic method for an operator, you can use that operator with objects of your class, and Python will automatically call the corresponding magic method to perform the operation.
Here's an example of overloading the + operator in a class:
class Point: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Point(self.x + other.x, self.y + other.y) p1 = Point(1, 2) p2 = Point(3, 4) p3 = p1 + p2 print(p3.x, p3.y) # Output: 4 6
In this example, we defined a Point class that has x and y coordinates. We also defined the add method to overload the + operator for adding two Point objects together. When we create two Point objects (p1 and p2) and add them together using the + operator, Python automatically calls the add method and returns a new Point object with the summed x and y coordinates.
This Particular section is dedicated to Question & Answer only. If you want learn more about Python. Then you can visit below links to get more depth on this subject.
Join Our telegram group to ask Questions
Click below button to join our groups.