Sobes.tech
Middle

What is operator overloading in Python?

sobes.tech AI

Answer from AI

Operator overloading is the ability to modify the behavior of built-in Python operators for user-defined class objects. It is achieved by defining special magic or dunder (double underscore) methods.

Here are some common magic methods for operator overloading:

Operator Magic method Description
+ __add__(self, other) Addition
- __sub__(self, other) Subtraction
* __mul__(self, other) Multiplication
/ __truediv__(self, other) True division
// __floordiv__(self, other) Floor division
% __mod__(self, other) Modulo
** __pow__(self, other) Exponentiation
== __eq__(self, other) Equality
!= __ne__(self, other) Inequality
< __lt__(self, other) Less than
> __gt__(self, other) Greater than
<= __le__(self, other) Less than or equal to
>= __ge__(self, other) Greater than or equal to
len() __len__(self) Length
str() __str__(self) String representation (for users)
repr() __repr__(self) String representation (for developers)

Example of overloading the + operator for a Vector class:

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

    # Overloading the + operator
    def __add__(self, other):
        if isinstance(other, Vector):
            return Vector(self.x + other.x, self.y + other.y)
        else:
            raise TypeError("Cannot add Vector and non-Vector type")

    # Adding a method for convenient output
    def __str__(self):
        return f"({self.x}, {self.y})"

# Creating Vector objects
v1 = Vector(1, 2)
v2 = Vector(3, 4)

# Using the overloaded + operator
v3 = v1 + v2

# Printing the result
print(v3)

Operator overloading makes code more readable and intuitive, allowing the use of familiar operators with user-defined objects. However, it should not be overused to avoid complicating code understanding.