Python Implement a Complex Number Class with Addition and Subtraction
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
- 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
)
(
"c1 + c2 ="
,
c1 + c2
)
(
"c1 - c2 ="
,
c1 - c2
)
Code analysis:
__init__method initializes the real and imaginary parts of the complex number.__add__method implements addition of complex numbers, returning a newComplexNumberobject.__sub__method implements subtraction of complex numbers, returning a newComplexNumberobject.__str__method converts the complex object into a string for convenient printing.
Output result:
c1 + c2 = 4 + 6i
c1 - c2 = 2 + 2i
Python3 Examples