24. Operator Overloading


1. Overloading + for Adding Two Objects

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

    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)

    def __repr__(self):
        return f"Vector({self.x}, {self.y})"

v1 = Vector(1, 2)
v2 = Vector(3, 4)
print(v1 + v2)  # Vector(4, 6)

2. Overloading - for Subtraction

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

    def __sub__(self, other):
        return Vector(self.x - other.x, self.y - other.y)

    def __repr__(self):
        return f"Vector({self.x}, {self.y})"

v1 = Vector(5, 7)
v2 = Vector(2, 3)
print(v1 - v2)  # Vector(3, 4)

3. Overloading * for Scalar Multiplication


4. Overloading / for Scalar Division


5. Overloading == for Equality Comparison


6. Overloading > for Greater Than Comparison


7. Overloading % for Custom Modulo Behavior


8. Overloading len() Using __len__


9. Overloading String Representation Using __str__


10. Overloading in Using __contains__


These examples illustrate how Python's special methods (dunder methods) allow you to redefine the behavior of built-in operators to work with custom classes, providing an intuitive and readable API.

Last updated