Implement a class in Python representing complex numbers, with addition, subtraction, etc.

Document 对象参考手册Python3 Examples

We will create a class namedComplexNumberto represent complex numbers. A complex number consists of a real part and an imaginary part. We will implement addition and subtraction operations.

Example

class ComplexNumber:
    def __init__(self, real, imaginary):
        self.real = real
        self.imaginary = imaginary

    def __add__(self, other):
        return ComplexNumber(self.real + other.real, self.imaginary + other.imaginary)

    def __sub__(self, other):
        return ComplexNumber(self.real - other.real, self.imaginary - other.imaginary)

    def __str__(self):
        return f"{self.real} + {self.imaginary}i"

# Example usage
c1 = ComplexNumber(3, 4)
c2 = ComplexNumber(1, 2)

print("c1 + c2 =", c1 + c2)
print("c1 - c2 =", c1 - c2)

Code explanation:

  1. __init__method is used to initialize the real and imaginary parts of the complex number.
  2. __add__method implements the addition operation of complex numbers, returning a newComplexNumberobject.
  3. __sub__method implements the subtraction operation of complex numbers, returning a newComplexNumberobject.
  4. __str__method is used to convert the complex number object into a string form, making it easy to print.

Output result:

c1 + c2 = 4 + 6i
c1 - c2 = 2 + 2i

Document 对象参考手册Python3 Examples

Other extensions