Write a python program to add objects + using operator


The python program defines a ComplexNumber class that represents complex numbers. It allows you to create complex number objects, display them as strings, and perform addition of two complex numbers using the + operator. Here's a breakdown of the code:

  • class ComplexNumber: This class represents a complex number with attributes real and imag, which represent the real and imaginary parts, respectively.
  • __init__(self, real, imag): The constructor initializes a ComplexNumber object with the provided real and imaginary parts.
  • __str__(self): This special method returns a string representation of the complex number in the format "a + bi" where 'a' is the real part, 'b' is the imaginary part, and 'i' denotes the imaginary unit.
  • __add__(self, other): This special method overloads the + operator, allowing you to add two complex numbers. It adds the real and imaginary parts separately and returns a new ComplexNumber object representing the sum.
  • Two complex number objects, complex1 and complex2, are created with different real and imaginary parts.
  • The code uses the + operator to add complex1 and complex2, resulting in a new ComplexNumber object called result.
  • The print statement displays the result of the addition, which is the sum of the complex numbers.

Here's what the code does:

  • It creates two complex number objects with different real and imaginary parts.
  • It adds these complex numbers using the + operator, which calls the __add__ method.
  • It prints the result of the addition.

Source Code

class ComplexNumber:
    def __init__(self, real, imag):
        self.real = real
        self.imag = imag
 
    def __str__(self):
        return str(self.real) + " + " + str(self.imag) + "i"
 
    def __add__(self, other):        
        real_part = self.real + other.real	# Add the real and imaginary parts separately
        imag_part = self.imag + other.imag
        return ComplexNumber(real_part, imag_part)
 
# Create two complex number objects
complex1 = ComplexNumber(3, 2)
complex2 = ComplexNumber(5, 3)
 
# Add the complex numbers using the + operator
result = complex1 + complex2
 
print("Addition :",result)

Output

Addition : 8 + 5i

Example Programs