Python Operator Overloading

1. What is Operator Overloading

Operator overloading allows custom classes to define how standard operators behave using special (dunder) methods.

class Number:
    def __init__(self, value):
        self.value = value

    def __add__(self, other):
        return self.value + other.value

n1 = Number(10)
n2 = Number(20)

print(n1 + n2)  # Output: 30

The + operator is redefined for the Number class.


2. Overloading the Addition Operator (+)

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

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

v1 = Vector(5)
v2 = Vector(7)
v3 = v1 + v2

print(v3.x)  # Output: 12

Implements vector addition logic.


3. Overloading the Subtraction Operator (-)

Custom logic for subtraction.


4. Overloading Multiplication Operator (*)

Defines how objects behave with *.


5. Overloading Division Operator (/)

Implements custom division logic.


6. Overloading Equality Operator (==)

Controls object comparison behavior.


7. Overloading Less Than and Greater Than

Supports sorting and ranking operations.


8. Overloading In-place Operators (+=)

Modifies object in-place.


9. Overloading String Representation (str())

Enhances readability of object display.


10. Comprehensive Operator Overloading Example

Fully custom arithmetic for a domain-specific class.


Last updated