Answer
Operator overloading is a feature that allows you to define the behaviour of operators, such as +, -, *, and /,when applied to objects of your own custom classes. It allows you to define how operators behave for objects of your own classes, just as you would for built-in data types like integers and strings.
For example, let's say you have a class that represents a complex number. By overloading the + operator, you can define how to add two complex numbers together.
Here's an example of operator overloading in Python:
Work Step by Step
class ComplexNumber:
$\hspace{4mm}$def __init__(self, real, imaginary):
$\hspace{8mm}$self.real = real
$\hspace{8mm}$self.imaginary = imaginary
$\hspace{4mm}$def __add__(self, other):
$\hspace{8mm}$return ComplexNumber(self.real + other.real, self.imaginary + other.imaginary)
# Create two ComplexNumbers
c1 = ComplexNumber(1, 2)
c2 = ComplexNumber(3, 4)
# Add the two ComplexNumbers
result = c1 + c2
# The result should be (4, 6)
print(result.real, result.imaginary)
In this example, the ComplexNumber class has an __add__ method that defines how two ComplexNumber objects should be added together. When you add two ComplexNumber objects using the + operator, the __add__ method is called to perform the addition.