Learn Object Oriented Programming by re-implementing Python’s Complex class: Part-3

leangaurav
Industrial Python
Published in
3 min readSep 3, 2019

The previous one covered usage of built-in complex class. It’s time to write our own code to handle complex numbers. This story focuses on creating and handling complex numbers using functions only. So the OO(Object Oriented Treatment) will come in the next part.

Before we get our hands dirty, lets see what all we will do.

  1. Represent complex numbers using a tuple.
  2. Write method to find conjugate and negate: Unary Operations
  3. Add and Subtract methods: Binary Operations
  4. Multiplication and Division

Complex number in a Tuple

We are going to put the real and imaginary part of a complex number into a tuple. So or representation for 1 + 2i will be (1,2). Element at index 0 will be real part and one at index 1 will be imaginary part.

For numbers having only real or imaginary part will be represented like this:

10 => (10, 0)
20i => (0,20)
-2i => (0,-2)

In Python we can create like this

To print these in a proper format lets define a function print_complex .

For negative imaginary part it looks weird. Update code looks like this

Looks better now !

Conjugate and Negative

Two simple functions will do our job.

Addition and Subtraction

That’s also quite easy to do. So just functions again.

Subtraction can also be implemented as addition of the negative. For now we have written it simple. In next part where we do the Object Oriented treatment, we will use that way.

Multiplication and Division

These operations are more complex than the previous ones. Multiplication is much more simpler to do than Division. See below code

For division we need help of previously defined function.

That’s it for this story. Next one covers Object Oriented treatment along with magic methods(operator overloading in python).

Prev: Complex Numbers 2: Python’s Complex class

Next: Complex Numbers 4: OOPS, Create Complex Class

--

--

leangaurav
Industrial Python

Engineer | Trainer | writes about Practical Software Engineering | Find me on linkedin.com/in/leangaurav | Discuss anything topmate.io/leangaurav