Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Implement a Complex Number Class with Addition and Subtraction

Python Implement a Complex Number Class with Addition and Subtraction

Document Object Reference Manual Python3 Examples

We will create a class named ComplexNumber class to represent complex numbers. A complex number consists of a real part and an imaginary part; we will implement addition and subtraction.

Example

class

ComplexNumber:

   

def

init

(

self

,

real

,

imaginary

)

:

       

self

.

real

=

real

       

self

.

imaginary

=

imaginary

   

def

add

(

self

,

other

)

:

       

return

ComplexNumber

(

self

.

real

real

,

self

.

imaginary

imaginary

)

   

def

sub

(

self

,

other

)

:

       

return

ComplexNumber

(

self

.

real

real

,

self

.

imaginary

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 analysis:

  1. __init__ method initializes the real and imaginary parts of the complex number.
  2. __add__ method implements addition of complex numbers, returning a new ComplexNumber object.
  3. __sub__ method implements subtraction of complex numbers, returning a new ComplexNumber object.
  4. __str__ method converts the complex object into a string for convenient printing.

Output result:

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

Document Object Reference Manual Python3 Examples