Operator Overloading

Carson West

Operators

Operator Overloading

Operator overloading allows you to define the behavior of built-in operators (like +, -, *, /, etc.) for user-defined types (classes). This makes your classes more intuitive and Pythonic.

How it works:

Operator overloading is achieved by defining special methods within your class. These methods have double underscores (__) at the beginning and end of their names (also known as “dunder” methods). For example:

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

    def __add__(self, other):  # Overloads the '+' operator
        return MyVector(self.x + other.x, self.y + other.y)

    def __str__(self): #Overloads the str() function.
        return f"({self.x}, {self.y})"

v1 = MyVector(1, 2)
v2 = MyVector(3, 4)
v3 = v1 + v2  # Uses the __add__ method
print(v3) # prints (4,6)
print(str(v3)) #prints (4,6)

Here, __add__ is overloaded to define the behavior of the + operator for MyVector objects. The + operator now performs vector addition.

Commonly Overloaded Operators and their corresponding methods:

Important Considerations:

Dunder Methods Error Handling in Python Magic Methods