Operator Overloading in Python

Mannan Ul Haq
0
In Python, like in other languages, operators can be overloaded to perform operations beyond their intended use, allowing user-defined objects to behave more like built-in data types. This is achieved using special methods, often referred to as "magic methods", that Python provides for this purpose.

The general structure for operator overloading in Python is:

class ClassName:
    def __magicmethod__(self, other):
        # body of code

Following is the list of some commonly overloaded operators and their corresponding magic methods in Python:

Operator Name Operator Symbol Magic Method
Addition+__add__
Subtraction-__sub__
Multiplication*__mul__
Division/__truediv__
Floor Division//__floordiv__
Modulus%__mod__
Power**__pow__
Bitwise AND&__and__
Bitwise OR|__or__
Bitwise XOR^__xor__
Bitwise NOT~__invert__
Left Bitwise Shift<<__lshift__
Right Bitwise Shift>>__rshift__
Equality==__eq__
Inequality!=__ne__
Greater than>__gt__
Less than<__lt__
Greater or equal>=__ge__
Less or equal<=__le__
In-place Addition+=__iadd__
In-place Subtraction-=__isub__
String Representationstr()__str__
Lengthlen()__len__
Get Item[]__getitem__
Set Item[]=__setitem__

Here is an example demonstrating operator overloading in Python:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    # Overloading the + operator
    def __add__(self, other):
        return Point(self.x + other.x, self.y + other.y)

    # Overloading the - operator
    def __sub__(self, other):
        return Point(self.x - other.x, self.y - other.y)

    # String representation of the object
    def __str__(self):
        return "({}, {})".format(self.x, self.y)

# Using the overloaded operators
p1 = Point(1, 2)
p2 = Point(3, 4)

print(p1 + p2)  # Output: (4, 6)
print(p1 - p2)  # Output: (-2, -2)

In the above example, the `+` and `-` operators are overloaded to work with `Point` objects. The `__str__` method is used to return a string representation of the object when it's printed.

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !